<template>
    <div class="app-container ios-style-container">
        <!-- 快速筛选区域 -->
        <div class="quick-filter-container" v-show="showSearch">
            <div class="quick-filter-title">
                <i class="el-icon-search"></i>
                <span>快速筛选</span>
            </div>
            <el-form :model="queryParams" ref="quickFilterForm" size="small" label-width="80px">
                <el-row :gutter="20">
                    <el-col :span="6">
                        <el-form-item label="订单号" prop="orderNo">
                            <el-input v-model="queryParams.orderNo" placeholder="请输入订单号" clearable
                                @keyup.enter.native="handleQuery" />
                        </el-form-item>
                    </el-col>
                    <el-col :span="6">
                        <el-form-item label="技术状态" prop="workStatus">
                            <el-select v-model="queryParams.workStatus" placeholder="请选择技术状态" clearable
                                style="width: 100%;">
                                <el-option v-for="dict in workStatusOptions" :key="dict.value" :label="dict.label"
                                    :value="dict.value" />
                            </el-select>
                        </el-form-item>
                    </el-col>
                    <el-col :span="6">
                        <el-form-item label="订单状态" prop="orderStatus">
                            <el-select v-model="queryParams.orderStatus" placeholder="请选择订单状态" clearable
                                style="width: 100%;">
                                <el-option v-for="dict in orderStatusOptions" :key="dict.value" :label="dict.label"
                                    :value="dict.value" />
                            </el-select>
                        </el-form-item>
                    </el-col>
                    <el-col :span="6">
                        <el-form-item>
                            <el-button type="primary" icon="el-icon-search" @click="handleQuery">搜索</el-button>
                            <el-button icon="el-icon-refresh" @click="resetQuery">重置</el-button>
                        </el-form-item>
                    </el-col>
                </el-row>
            </el-form>
        </div>

        <el-form :model="queryParams" ref="queryForm" size="small" v-show="showSearch" label-width="auto">
            <el-collapse v-model="activeNames" style="width: 100%; border: none; padding: 0 10px;">
                <el-collapse-item name="filter" style="border: none;">
                    <template slot="title">
                        <span
                            style="font-size: 16px; text-align: center; width: 100%; font-family: 'PingFang-SC', sans-serif; padding-left: 10px;">
                            筛选条件
                        </span>
                    </template>
                    <div
                        style="display: grid; grid-template-columns: repeat(auto-fill, minmax(300px, 1fr)); gap: 10px; padding: 0 10px;">


                        <div style="display: flex; align-items: center; gap: 10px; flex-wrap: wrap;">
                            <el-form-item label="订单标题" prop="orderTitle"
                                style="margin-bottom: 5px; flex: 1; min-width: 200px;">
                                <el-input v-model="queryParams.orderTitle" placeholder="订单标题" clearable
                                    @keyup.enter.native="handleQuery" />
                            </el-form-item>
                        </div>

                        <div style="display: flex; align-items: center; gap: 10px; flex-wrap: wrap;">
                            <el-form-item label="学校" prop="school"
                                style="margin-bottom: 5px; flex: 1; min-width: 200px;">
                                <el-input v-model="queryParams.school" placeholder="学校" clearable
                                    @keyup.enter.native="handleQuery" />
                            </el-form-item>
                        </div>

                        <div style="display: flex; align-items: center; gap: 10px; flex-wrap: wrap;">
                            <el-form-item label="项目类型" prop="projectType"
                                style="margin-bottom: 5px; flex: 1; min-width: 200px;">
                                <el-select v-model="queryParams.projectType" placeholder="项目类型" clearable
                                    style="width: 100%;">
                                    <el-option v-for="dict in projectTypeOptions" :key="dict.value" :label="dict.label"
                                        :value="dict.value" />
                                </el-select>
                            </el-form-item>
                        </div>
                        <div style="display: flex; align-items: center; gap: 10px; flex-wrap: wrap;">
                            <el-form-item label="订单金额" style="margin-bottom: 5px; flex: 1; min-width: 200px;">
                                <div style="display: flex; align-items: center; gap: 5px; width: 100%;">
                                    <el-input v-model="minRewardAmount" placeholder="最低金额" clearable
                                        @keyup.enter.native="handleQuery" />
                                    <span>-</span>
                                    <el-input v-model="maxRewardAmount" placeholder="最高金额" clearable
                                        @keyup.enter.native="handleQuery" />
                                </div>
                            </el-form-item>
                        </div>


                        <div style="display: flex; align-items: center; gap: 10px; flex-wrap: wrap;">
                            <el-form-item label="程序类型" prop="techType"
                                style="margin-bottom: 5px; flex: 1; min-width: 200px;">
                                <el-select v-model="queryParams.techType" placeholder="程序类型" clearable filterable
                                    style="width: 100%;">
                                    <el-option v-for="dict in techTypeOptions" :key="dict.value" :label="dict.label"
                                        :value="dict.value" />
                                </el-select>
                            </el-form-item>
                        </div>




                        <div style="display: flex; align-items: center; gap: 10px; flex-wrap: wrap;">
                            <el-form-item label="是否加急" prop="isUrgent"
                                style="margin-bottom: 5px; flex: 1; min-width: 200px;">
                                <el-select v-model="queryParams.isUrgent" placeholder="是否加急" clearable
                                    style="width: 100%;">
                                    <el-option v-for="dict in isUrgentOptions" :key="dict.value" :label="dict.label"
                                        :value="dict.value" />
                                </el-select>
                            </el-form-item>
                        </div>



                        <div style="display: flex; align-items: center; gap: 10px; flex-wrap: wrap;">
                            <el-form-item label="售前姓名" prop="preSalesId"
                                style="margin-bottom: 5px; flex: 1; min-width: 200px;">
                                <el-select v-model="queryParams.preSalesId" placeholder="售前姓名" clearable filterable
                                    style="width: 100%;">
                                    <el-option v-for="user in preSaleUserOptions" :key="user.value" :label="user.label"
                                        :value="user.value" />
                                </el-select>
                            </el-form-item>
                        </div>

                        <div style="display: flex; align-items: center; gap: 10px; flex-wrap: wrap;">
                            <el-form-item label="售中姓名" prop="inSaleId"
                                style="margin-bottom: 5px; flex: 1; min-width: 200px;">
                                <el-select v-model="queryParams.inSaleId" placeholder="售中姓名" clearable filterable
                                    style="width: 100%;">
                                    <el-option v-for="user in inSaleUserOptions" :key="user.value" :label="user.label"
                                        :value="user.value" />
                                </el-select>
                            </el-form-item>
                        </div>

                        <div style="display: flex; align-items: center; gap: 10px; flex-wrap: wrap;">
                            <el-form-item label="售后姓名" prop="afterSaleId"
                                style="margin-bottom: 5px; flex: 1; min-width: 200px;">
                                <el-select v-model="queryParams.afterSaleId" placeholder="售后姓名" clearable filterable
                                    style="width: 100%;">
                                    <el-option v-for="user in afterSaleUserOptions" :key="user.value"
                                        :label="user.label" :value="user.value" />
                                </el-select>
                            </el-form-item>
                        </div>

                        <div style="display: flex; align-items: center; gap: 10px; flex-wrap: wrap;">
                            <el-form-item label="技术筛选" prop="acceptedProgrammerId"
                                style="margin-bottom: 5px; flex: 1; min-width: 200px;">
                                <el-select v-model="queryParams.acceptedProgrammerId" placeholder="技术筛选" clearable
                                    filterable style="width: 100%;">
                                    <el-option v-for="user in techUserOptions" :key="user.value" :label="user.label"
                                        :value="user.value" />
                                </el-select>
                            </el-form-item>
                        </div>

                        <div style="display: flex; align-items: center; gap: 10px; flex-wrap: wrap;">
                            <el-form-item label="包单时间" style="margin-bottom: 5px; flex: 1; min-width: 200px;">
                                <el-date-picker v-model="daterangeStartTime" style="width: 100%"
                                    value-format="yyyy-MM-dd" type="daterange" range-separator="-"
                                    start-placeholder="开始日期" end-placeholder="结束日期">
                                </el-date-picker>
                            </el-form-item>
                        </div>

                        <div style="display: flex; align-items: center; gap: 10px; flex-wrap: wrap;">
                            <el-form-item label="接单时间" style="margin-bottom: 5px; flex: 1; min-width: 200px;">
                                <el-date-picker v-model="daterangeAcceptTime" style="width: 100%"
                                    value-format="yyyy-MM-dd" type="daterange" range-separator="-"
                                    start-placeholder="开始日期" end-placeholder="结束日期">
                                </el-date-picker>
                            </el-form-item>
                        </div>

                        <div style="display: flex; align-items: center; gap: 10px; flex-wrap: wrap;">
                            <el-form-item label="交付时间" style="margin-bottom: 5px; flex: 1; min-width: 200px;">
                                <el-date-picker v-model="daterangeEstimatedEndTime" style="width: 100%"
                                    value-format="yyyy-MM-dd" type="daterange" range-separator="-"
                                    start-placeholder="开始日期" end-placeholder="结束日期">
                                </el-date-picker>
                            </el-form-item>
                        </div>
                    </div>

                    <el-form-item style="margin-top: 10px; padding: 0 10px;">
                        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
                        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
                    </el-form-item>
                </el-collapse-item>
            </el-collapse>
        </el-form>

        <el-row :gutter="10" class="mb8">
            <el-col :span="1.5">
                <el-button type="primary" plain icon="el-icon-plus" size="mini" @click="handleAdd"
                    v-hasPermi="['dashboard:orders:add']">新增</el-button>
            </el-col>
            <el-col :span="1.5">
                <el-button type="success" plain icon="el-icon-edit" size="mini" :disabled="single" @click="handleUpdate"
                    v-hasPermi="['dashboard:orders:edit']">编辑</el-button>
            </el-col>
            <el-col :span="1.5">
                <el-button type="danger" plain icon="el-icon-delete" size="mini" :disabled="multiple"
                    @click="handleDelete" v-hasPermi="['dashboard:orders:remove']">删除</el-button>
            </el-col>
            <el-col :span="1.5">
                <el-button type="warning" plain icon="el-icon-download" size="mini" @click="handleExport"
                    v-hasPermi="['dashboard:orders:export']">导出</el-button>
            </el-col>
            <el-col :span="1.5">
                <el-dropdown @command="handleSort" trigger="click">
                    <el-button size="mini" type="primary" plain>
                        排序<i class="el-icon-arrow-down el-icon--right"></i>
                    </el-button>
                    <el-dropdown-menu slot="dropdown">
                        <el-dropdown-item command="accept_time.asc">接单时间升序</el-dropdown-item>
                        <el-dropdown-item command="accept_time.desc">接单时间降序</el-dropdown-item>
                        <el-dropdown-item command="estimated_end_time.asc">截止时间升序</el-dropdown-item>
                        <el-dropdown-item command="estimated_end_time.desc">截止时间降序</el-dropdown-item>
                    </el-dropdown-menu>
                </el-dropdown>
            </el-col>
            <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
            <span class="order-total-value"></span>
        </el-row>

        <!-- 统计数据行 -->
        <el-row class="statistics-row">
            <el-col :span="1.5">
                <div class="status-counts-container" style="padding-left: 20px;">
                    <!-- <div class="status-count-item">
            <span class="status-label">订单总数</span>
            <el-tag size="medium" class="status-count-tag tag-white-black">{{ total}}</el-tag>
          </div> -->
                    <div class="status-count-item">
                        <span class="status-label">未开发数</span>
                        <el-tag size="medium" class="status-count-tag tag-white-black">{{ statistics.notDevelopedCount
                            || 0
                            }}</el-tag>
                    </div>
                    <div class="status-count-item">
                        <span class="status-label">已开发数</span>
                        <el-tag size="medium" class="status-count-tag tag-white-black">{{ statistics.developedCount || 0
                            }}</el-tag>
                    </div>
                    <div class="status-count-item">
                        <span class="status-label">未过售后期移交数</span>
                        <el-tag size="medium" class="status-count-tag tag-blue-black">{{
                            statistics.unexpiredAfterSaleHandoverCount || 0 }}</el-tag>
                    </div>
                    <div class="status-count-item">
                        <span class="status-label">未过售后期价格</span>
                        <el-tag size="medium" class="status-count-tag tag-blue-black">¥{{
                            statistics.unexpiredAfterSaleAmount ||
                            0 }}</el-tag>
                    </div>
                    <div class="status-count-item">
                        <span class="status-label">最终成交数</span>
                        <el-tag size="medium" class="status-count-tag tag-red-black">{{ statistics.finalDealCount || 0
                            }}</el-tag>
                    </div>
                    <div class="status-count-item">
                        <span class="status-label">最终成交价</span>
                        <el-tag size="medium" class="status-count-tag"
                            :class="parseFloat(statistics.finalDealDifference || 0) >= 0 ? 'tag-green-black' : 'tag-red-black'">
                            {{ parseFloat(statistics.finalDealDifference || 0) >= 0 ? '' : '' }}¥{{
                                statistics.finalDealDifference || 0 }}
                        </el-tag>
                    </div>

                    <div class="status-count-item">
                        <span class="status-label">黄单数</span>
                        <el-tag size="medium" class="status-count-tag tag-yellow-black">{{ statistics.yellowOrderCount
                            || 0
                            }}</el-tag>
                    </div>
                    <div class="status-count-item">
                        <span class="status-label">黄单率</span>
                        <el-tag size="medium" class="status-count-tag tag-yellow-black">{{ (statistics.yellowOrderRate *
                            100).toFixed(2) + '%' || '0.00%' }}</el-tag>
                    </div>
                    <div class="status-count-item">
                        <span class="status-label">服务费数</span>
                        <el-tag size="medium" class="status-count-tag tag-yellow-black">{{
                            statistics.serviceChargeCount }}</el-tag>
                    </div>
                    <div class="status-count-item">
                        <span class="status-label">服务费</span>
                        <el-tag size="medium" class="status-count-tag tag-yellow-black">¥{{ statistics.serviceCharge ||
                            0
                            }}</el-tag>
                    </div>
                    <div class="status-count-item">
                        <span class="status-label">服务费利润</span>
                        <el-tag size="medium" class="status-count-tag"
                            :class="parseFloat(statistics.serviceChargeProfit || 0) >= 0 ? 'tag-green-black' : 'tag-red-black'">
                            {{ parseFloat(statistics.serviceChargeProfit || 0) >= 0 ? '' : '' }}¥{{
                                statistics.serviceChargeProfit || 0 }}
                        </el-tag>
                    </div>
                    <!-- <div class="status-count-item">
            <span class="status-label">成品个数</span>
            <el-tag size="medium" class="status-count-tag tag-yellow-black">{{ statistics.finalDealCount || 0 }}</el-tag>
          </div> -->
                    <div class="status-count-item">
                        <span class="status-label">实付金额总价</span>
                        <el-tag size="medium" class="status-count-tag tag-yellow-black">¥{{
                            statistics.completedDealDifference
                            || 0 }}</el-tag>
                    </div>
                    <!-- <div class="status-count-item">
            <span class="status-label">总计:</span>
            <el-tag type="primary" size="medium">{{ total }}</el-tag>
          </div> -->
                </div>
            </el-col>
        </el-row>

        <div class="table-wrapper">
            <el-table :row-class-name="tableRowClassName" v-loading="loading" :data="ordersList"
                @selection-change="handleSelectionChange" height="100%" :cell-class-name="tableCellClassName">
                <el-table-column type="selection" width="55" align="center" fixed="left" />
                <el-table-column label="订单号" align="center" prop="orderNo" width="180" fixed="left" />
                <!-- 新增售中进度列 -->
                <el-table-column label="售中进度" align="center" prop="inSaleProgress" width="120">
                    <template slot-scope="scope">
                        <el-popover trigger="hover" placement="top" v-if="scope.row.inSaleProgress">
                            <div style="max-height: 200px; overflow-y: auto;">
                                {{ scope.row.inSaleProgress }}
                            </div>
                            <div slot="reference" class="introduce-text">
                                {{ scope.row.inSaleProgress | truncate(8) }}
                            </div>
                        </el-popover>
                        <span v-else class="introduce-text" style="color: #C0C4CC;">暂无进度</span>
                    </template>
                </el-table-column>
                <!-- 新增售后进度列 -->
                <el-table-column label="售后进度" align="center" prop="afterSaleProgress" width="120">
                    <template slot-scope="scope">
                        <el-popover trigger="hover" placement="top" v-if="scope.row.afterSaleProgress">
                            <div style="max-height: 200px; overflow-y: auto;">
                                {{ scope.row.afterSaleProgress }}
                            </div>
                            <div slot="reference" class="introduce-text">
                                {{ scope.row.afterSaleProgress | truncate(8) }}
                            </div>
                        </el-popover>
                        <span v-else class="introduce-text" style="color: #C0C4CC;">暂无进度</span>
                    </template>
                </el-table-column>
                <!-- 新增完成进度列 -->
                <el-table-column label="完成进度" align="center" prop="completionStatus" width="120">
                    <template slot-scope="scope">
                        <el-tag v-if="scope.row.completionStatus === 1" type="success" size="small">初稿已完成</el-tag>
                        <el-tag v-else-if="scope.row.completionStatus === 2" type="warning" size="small">修改中</el-tag>
                        <el-tag v-else-if="scope.row.completionStatus === 3" type="primary" size="small">终稿已确认</el-tag>
                        <el-tag v-else type="info" size="small">未设置</el-tag>
                    </template>
                </el-table-column>
                <!-- 修改订单标题列 -->
                <el-table-column label="订单标题" align="center" prop="orderTitle" width="150">
                    <template slot-scope="scope">
                        <el-popover trigger="hover" placement="top">
                            <div style="max-height: 200px; overflow-y: auto;">
                                {{ scope.row.orderTitle }}
                            </div>
                            <div slot="reference" class="introduce-text">
                                {{ scope.row.orderTitle | truncate(5) }}
                            </div>
                        </el-popover>
                    </template>
                </el-table-column>

                <!-- 新增店铺名称列 -->
                <el-table-column label="店铺名称" align="center" prop="storeName" width="120">
                    <template slot-scope="scope">
                        <el-popover trigger="hover" placement="top">
                            <div>{{ scope.row.storeName }}</div>
                            <div slot="reference" class="introduce-text">
                                {{ scope.row.storeName | truncate(5) }}
                            </div>
                        </el-popover>
                    </template>
                </el-table-column>

                <!-- 新增客户旺旺号列 -->
                <el-table-column label="客户旺旺号" align="center" prop="customerWangwangId" width="120">
                    <template slot-scope="scope">
                        <el-popover trigger="hover" placement="top">
                            <div>{{ scope.row.customerWangwangId }}</div>
                            <div slot="reference" class="introduce-text">
                                {{ scope.row.customerWangwangId | truncate(5) }}
                            </div>
                        </el-popover>
                    </template>
                </el-table-column>

                <el-table-column label="客户姓名" align="center" prop="customerName" />
                <el-table-column label="客户电话" align="center" prop="customerPhone" />
                <el-table-column label="学校" align="center" prop="school" />
                <el-table-column label="专业" align="center" prop="specialty" />
                <el-table-column label="项目类型" align="center" prop="projectType" />
                <!-- 修改硬件环境列 -->
                <el-table-column label="硬件环境" align="center" prop="hardware" width="120">
                    <template slot-scope="scope">
                        <el-popover trigger="hover" placement="top">
                            <div>{{ scope.row.hardware }}</div>
                            <div slot="reference" class="introduce-text">
                                {{ scope.row.hardware | truncate(5) }}
                            </div>
                        </el-popover>
                    </template>
                </el-table-column>

                <el-table-column label="程序类型" align="center" prop="techType" />
                <el-table-column label="是否加急" align="center" prop="isUrgent">
                    <template slot-scope="scope">
                        <el-tag :type="scope.row.isUrgent === '1' ? 'danger' : 'info'" size="small">{{
                            selectDictLabel(isUrgentOptions, scope.row.isUrgent) }}</el-tag>
                    </template>
                </el-table-column>
                <el-table-column label="技术状态" align="center" prop="workStatus">
                    <template slot-scope="scope">
                        <span>{{ selectDictLabel(workStatusOptions, scope.row.workStatus) }}</span>
                    </template>
                </el-table-column>
                <!-- 新增售前接单价列 -->
                <el-table-column label="售前接单价" align="center" prop="preSalesAmount">
                    <template slot-scope="scope">
                        <span>¥{{ scope.row.preSalesAmount || 0 }}</span>
                    </template>
                </el-table-column>

                <!-- 新增售中加价列 -->
                <el-table-column label="售中加价" align="center" prop="inSalesAmount">
                    <template slot-scope="scope">
                        <span>¥{{ scope.row.inSalesAmount || 0 }}</span>
                    </template>
                </el-table-column>

                <!-- 新增售后加价列 -->
                <el-table-column label="售后加价" align="center" prop="afterSalesAmount">
                    <template slot-scope="scope">
                        <span>¥{{ scope.row.afterSalesAmount || 0 }}</span>
                    </template>
                </el-table-column>

                <el-table-column label="订单总价" align="center" prop="rewardAmount">
                    <template slot-scope="scope">
                        <span>¥{{ scope.row.rewardAmount || 0 }}</span>
                    </template>
                </el-table-column>

                <!-- 新增包单价格列 -->
                <el-table-column label="包单价格" align="center" prop="packageAmount" width="120">
                    <template slot-scope="scope">
                        <span>¥{{ scope.row.packageAmount || 0 }}</span>
                    </template>
                </el-table-column>

                <!-- 新增利润差价列 -->
                <el-table-column label="利润差价" align="center" prop="profitDifference" width="120">
                    <template slot-scope="scope">
                        <span :style="{
                            color: (scope.row.profitDifference || 0) >= 0 ? '#67C23A' : '#F56C6C',
                            fontWeight: 'bold'
                        }">
                            {{ (scope.row.profitDifference || 0) >= 0 ? '+' : '' }}¥{{ scope.row.profitDifference || 0
                            }}
                        </span>
                    </template>
                </el-table-column>

                <!-- 新增服务费列 -->
                <el-table-column label="服务费" align="center" prop="serviceCharge">
                    <template slot-scope="scope">
                        <span>¥{{ (scope.row.serviceCharge || 0).toFixed(2) }}</span>
                    </template>
                </el-table-column>

                <el-table-column label="实付金额" align="center" prop="realMoney" />
                <el-table-column label="状态" align="center" prop="orderStatus">
                    <template slot-scope="scope">
                        <span>{{ selectDictLabel(orderStatusOptions, scope.row.orderStatus) }}</span>
                    </template>
                </el-table-column>
                <el-table-column label="收款状态" align="center" prop="orderStatusAmount">
                    <template slot-scope="scope">
                        <el-tag :type="scope.row.orderStatusAmount === '4' ? 'danger' : 'info'" size="small">
                            {{ selectDictLabel(orderStatusAmountOptions, scope.row.orderStatusAmount) }}
                        </el-tag>
                    </template>
                </el-table-column>
                <el-table-column label="技能要求" align="center" prop="requiredSkillLevelId">
                    <template slot-scope="scope">
                        <span>{{ selectDictLabel(skillLevelOptions, scope.row.requiredSkillLevelId) }}</span>
                    </template>
                </el-table-column>
                <el-table-column label="信用分" align="center" prop="requiredCreditScore" />
                <el-table-column label="售前" align="center" prop="preSalesName" />
                <el-table-column label="售中" align="center" prop="inSaleName" />
                <el-table-column label="售后" align="center" prop="afterSaleName" />
                <!-- 修改程序员列 -->
                <el-table-column label="程序员" align="center" prop="acceptedProgrammerName" width="120">
                    <template slot-scope="scope">
                        <el-popover trigger="hover" placement="top"
                            v-if="scope.row.acceptedProgrammerId || scope.row.acceptedProgrammerName">
                            <div style="max-width: 400px; word-break: break-all; line-height: 1.5;">
                                {{ formatProgrammerInfo(scope.row) }}
                            </div>
                            <div slot="reference" class="introduce-text">
                                {{ formatProgrammerInfo(scope.row) | truncate(8) }}
                            </div>
                        </el-popover>
                        <span v-else class="introduce-text" style="color: #C0C4CC;">未分配</span>
                    </template>
                </el-table-column>
                <el-table-column label="预计完成" align="center" prop="estimatedEndTime">
                    <template slot-scope="scope">
                        <span>{{ parseTime(scope.row.estimatedEndTime, '{y}-{m}-{d}') }}</span>
                    </template>
                </el-table-column>
                <el-table-column label="创建时间" align="center" prop="createTime">
                    <template slot-scope="scope">
                        <span>{{ parseTime(scope.row.createTime) }}</span>
                    </template>
                </el-table-column>
                <el-table-column label="更新时间" align="center" prop="updateTime">
                    <template slot-scope="scope">
                        <span>{{ parseTime(scope.row.updateTime) }}</span>
                    </template>
                </el-table-column>
                <!-- <el-table-column label="简介" align="center" prop="introduce" /> -->
                <el-table-column label="简介" align="center" prop="introduce" width="200">
                    <template slot-scope="scope">
                        <el-popover trigger="hover" placement="top">
                            <div style="max-height: 200px; overflow-y: auto;">
                                {{ scope.row.introduce }}
                            </div>
                            <div slot="reference" class="introduce-text">
                                {{ scope.row.introduce | truncate(5) }}
                            </div>
                        </el-popover>
                    </template>
                </el-table-column>
                <!-- 修改交付物列 -->
                <el-table-column label="交付物" align="center" prop="deliverable" width="150">
                    <template slot-scope="scope">
                        <el-popover trigger="hover" placement="top">
                            <div style="max-height: 200px; overflow-y: auto;">
                                {{ scope.row.deliverable }}
                            </div>
                            <div slot="reference" class="introduce-text">
                                {{ scope.row.deliverable | truncate(5) }}
                            </div>
                        </el-popover>
                    </template>
                </el-table-column>
                <!-- 修改退单理由列 -->
                <el-table-column label="退单理由" align="center" prop="chargebackReason" width="150">
                    <template slot-scope="scope">
                        <el-popover trigger="hover" placement="top">
                            <div style="max-height: 200px; overflow-y: auto;">
                                {{ scope.row.chargebackReason }}
                            </div>
                            <div slot="reference" class="introduce-text">
                                {{ scope.row.chargebackReason | truncate(5) }}
                            </div>
                        </el-popover>
                    </template>
                </el-table-column>

                <!-- 收款图片列 -->
                <el-table-column label="收款图片" align="center" prop="receiptImages" width="120">
                    <template slot-scope="scope">
                        <div v-if="scope.row.receiptImages">
                            <el-image v-for="(image, index) in scope.row.receiptImages.split(',').slice(0, 1)"
                                :key="index" :src="image" :preview-src-list="scope.row.receiptImages.split(',')"
                                fit="cover"
                                style="width: 30px; height: 30px; margin: 2px; border-radius: 4px; cursor: pointer;">
                            </el-image>
                            <span v-if="scope.row.receiptImages.split(',').length > 1"
                                style="font-size: 12px; color: #909399;">
                                +{{ scope.row.receiptImages.split(',').length - 1 }}
                            </span>
                        </div>
                        <span v-else style="color: #C0C4CC;">暂无图片</span>
                    </template>
                </el-table-column>

                <!-- 需求图片列 -->
                <el-table-column label="需求图片" align="center" prop="demandUrl" width="120">
                    <template slot-scope="scope">
                        <div v-if="scope.row.demandUrl">
                            <el-image v-for="(image, index) in scope.row.demandUrl.split(',').slice(0, 1)"
                                :key="index" :src="image" :preview-src-list="scope.row.demandUrl.split(',')"
                                fit="cover"
                                style="width: 30px; height: 30px; margin: 2px; border-radius: 4px; cursor: pointer;">
                            </el-image>
                            <span v-if="scope.row.demandUrl.split(',').length > 1"
                                style="font-size: 12px; color: #909399;">
                                +{{ scope.row.demandUrl.split(',').length - 1 }}
                            </span>
                        </div>
                        <span v-else style="color: #C0C4CC;">暂无图片</span>
                    </template>
                </el-table-column>
                <!-- <el-table-column label="备注" align="center" prop="remark" /> -->
                <el-table-column label="操作" align="center" class-name="small-padding fixed-width" width="340"
                    fixed="right">
                    <template slot-scope="scope">
                        <el-button size="mini" type="text" icon="el-icon-edit" @click="handleUpdate(scope.row)"
                            v-hasPermi="['dashboard:orders:edit']">编辑</el-button>
                        <el-button size="mini" type="text" icon="el-icon-delete" @click="handleDelete(scope.row)"
                            v-hasPermi="['dashboard:orders:remove']">删除</el-button>
                        <el-button size="mini" type="text" icon="el-icon-upload"
                            @click="handleUpload(scope.row)">文件</el-button>
                        <el-button size="mini" type="text" icon="el-icon-money"
                            @click="handleRefund(scope.row)">退款</el-button>
                        <el-button size="mini" type="text" icon="el-icon-picture"
                            @click="handleReceiptImages(scope.row)">收款图</el-button>
                        <el-button size="mini" type="text" icon="el-icon-picture-outline"
                            @click="handleDemandImages(scope.row)">需求图</el-button>
                        <el-button size="mini" type="text" icon="el-icon-s-promotion"
                            @click="handlePublishTask(scope.row)" v-hasPermi="['dashboard:task:add']">发布任务</el-button>
                        <el-button size="mini" type="text" icon="el-icon-check"
                            @click="handleTechnicalDelivery(scope.row)" v-hasPermi="['dashboard:orders:edit']"
                            v-if="hasAfterSalePermission && scope.row.orderStatus === '2'">技术交付</el-button>
                        <el-button size="mini" type="text" icon="el-icon-success"
                            @click="handleCustomerConfirm(scope.row)" v-hasPermi="['dashboard:orders:edit']"
                            v-if="hasAfterSalePermission && scope.row.orderStatus === '6'">客户确认</el-button>
                        <el-dropdown @command="(command) => handleCompletionStatusSwitch(scope.row, command)" trigger="click" 
                            v-hasPermi="['dashboard:orders:edit']">
                            <el-button size="mini" type="text" icon="el-icon-refresh">
                                完成进度<i class="el-icon-arrow-down el-icon--right"></i>
                            </el-button>
                            <el-dropdown-menu slot="dropdown">
                                <el-dropdown-item command="1" 
                                    :disabled="scope.row.completionStatus === 1">初稿已完成</el-dropdown-item>
                                <el-dropdown-item command="2" 
                                    :disabled="!scope.row.completionStatus || scope.row.completionStatus < 1">修改中</el-dropdown-item>
                                <el-dropdown-item command="3" 
                                    :disabled="!scope.row.completionStatus || scope.row.completionStatus < 1">终稿已确认</el-dropdown-item>
                            </el-dropdown-menu>
                        </el-dropdown>
                    </template>
                </el-table-column>
            </el-table>
        </div>

        <!-- <pagination  :total="total"  /> -->

        <pagination v-show="total > 0" :total="total" :page.sync="queryParams.pageNum"
            :limit.sync="queryParams.pageSize" :page-sizes="[10, 20, 30, 50, 100, 200, 500, 1000, 2000, 5000, 10000]" @pagination="getList" />

        <!-- 添加或修改订单主表对话框 -->
        <el-dialog :title="title" :visible.sync="open" width="800px" append-to-body>
            <el-form ref="form" :model="form" :rules="rules" label-width="120px">
                <el-row>
                    <el-col :span="12">
                        <el-form-item label="订单号" prop="orderNo">
                            <el-input v-model="form.orderNo" placeholder="请输入订单号" />
                        </el-form-item>
                    </el-col>
                    <el-col :span="12">
                        <el-form-item label="订单标题" prop="orderTitle">
                            <el-input v-model="form.orderTitle" placeholder="请输入订单标题" />
                        </el-form-item>
                    </el-col>
                </el-row>
                <el-row>
                    <el-col :span="12">
                        <el-form-item label="店铺名称" prop="storeName">
                            <el-select v-model="form.storeName" placeholder="请输入店铺名称">
                                <el-option v-for="dict in dict.type.store" :key="dict.value" :label="dict.label"
                                    :value="dict.value"></el-option>
                            </el-select>
                        </el-form-item>
                    </el-col>
                    <el-col :span="12">
                        <el-form-item label="客户旺旺号" prop="customerWangwangId">
                            <el-input v-model="form.customerWangwangId" placeholder="请输入客户旺旺号" />
                        </el-form-item>
                    </el-col>
                </el-row>
                <el-row>
                    <el-col :span="12">
                        <el-form-item label="客户姓名" prop="customerName">
                            <el-input v-model="form.customerName" placeholder="请输入客户姓名" />
                        </el-form-item>
                    </el-col>
                    <el-col :span="12">
                        <el-form-item label="客户联系方式" prop="customerPhone">
                            <el-input v-model="form.customerPhone" placeholder="请输入客户联系方式" />
                        </el-form-item>
                    </el-col>
                </el-row>
                <el-row>
                    <el-col :span="12">
                        <el-form-item label="学校" prop="school">
                            <el-input v-model="form.school" placeholder="请输入学校" />
                        </el-form-item>
                    </el-col>
                    <el-col :span="12">
                        <el-form-item label="专业" prop="specialty">
                            <el-input v-model="form.specialty" placeholder="请输入专业" />
                        </el-form-item>
                    </el-col>
                </el-row>
                <el-row>
                    <el-col :span="12">
                        <el-form-item label="项目类型" prop="projectType">
                            <el-select v-model="form.projectType" placeholder="请选择项目类型" style="width:100%;">
                                <el-option v-for="dict in projectTypeOptions" :key="dict.value" :label="dict.label"
                                    :value="dict.value" />
                            </el-select>
                        </el-form-item>
                    </el-col>
                    <el-col :span="12">
                        <el-form-item label="硬件环境" prop="hardware">
                            <el-input v-model="form.hardware" placeholder="请输入硬件环境" />
                        </el-form-item>
                    </el-col>
                </el-row>
                <el-row>
                    <el-col :span="12">
                        <el-form-item label="是否加急" prop="isUrgent">
                            <el-select v-model="form.isUrgent" placeholder="请选择是否加急">
                                <el-option v-for="dict in isUrgentOptions" :key="dict.value" :label="dict.label"
                                    :value="dict.value"></el-option>
                            </el-select>
                        </el-form-item>
                    </el-col>
                    <el-col :span="12">
                        <el-form-item label="程序类型" prop="techType">
                            <el-select v-model="form.techType" placeholder="请选择程序类型" style="width:100%;" filterable>
                                <el-option v-for="dict in techTypeOptions" :key="dict.value" :label="dict.label"
                                    :value="dict.value" />
                            </el-select>
                        </el-form-item>
                    </el-col>
                </el-row>
                <el-row>
                    <!-- <el-col :span="12">
            <el-form-item label="开始时间" prop="startTime">
              <el-date-picker clearable v-model="form.startTime" type="date" value-format="yyyy-MM-dd"
                placeholder="请选择程序开始时间">
              </el-date-picker>
            </el-form-item>
          </el-col> -->
                    <el-col :span="12">
                        <el-form-item label="截止时间" prop="estimatedEndTime">
                            <el-date-picker clearable v-model="form.estimatedEndTime" type="date"
                                value-format="yyyy-MM-dd" placeholder="请选择截止时间">
                            </el-date-picker>
                        </el-form-item>
                    </el-col>
                    <el-col :span="12">
                        <el-form-item label="中期付款时间" prop="midPaymentTime">
                            <el-date-picker clearable v-model="form.midPaymentTime" type="date"
                                value-format="yyyy-MM-dd" placeholder="请选择中期付款时间">
                            </el-date-picker>
                        </el-form-item>
                    </el-col>
                </el-row>
                <el-row>
                    <el-col :span="12">
                        <el-form-item label="售前接单价" prop="preSalesAmount">
                            <el-input-number :precision="2" :step="100" v-model="form.preSalesAmount"
                                placeholder="请输入售前接单价" @change="calculateTotalAmount" />
                        </el-form-item>
                    </el-col>
                    <el-col :span="12">
                        <el-form-item label="售中加价" prop="inSalesAmount">
                            <el-input-number :precision="2" :step="100" v-model="form.inSalesAmount"
                                placeholder="请输入售中加价" @change="calculateTotalAmount" />
                        </el-form-item>
                    </el-col>
                </el-row>
                <el-row>
                    <el-col :span="12">
                        <el-form-item label="售后加价" prop="afterSalesAmount">
                            <el-input-number :precision="2" :step="100" v-model="form.afterSalesAmount"
                                placeholder="请输入售后加价" @change="calculateTotalAmount" />
                        </el-form-item>
                    </el-col>
                    <el-col :span="12">
                        <el-form-item label="订单总金额" prop="rewardAmount">
                            <el-input-number :precision="2" :step="100" v-model="form.rewardAmount"
                                placeholder="自动计算(售前接单价+售中加价+售后加价)" disabled readonly />
                        </el-form-item>
                    </el-col>
                </el-row>
                <el-row>
                    <el-col :span="12">
                        <el-form-item label="服务费" prop="serviceCharge">
                            <el-input-number 
                                v-model="form.serviceCharge" 
                                :min="0"
                                :precision="2" 
                                :step="100"
                                controls-position="right"
                                style="width: 100%"
                                placeholder="请输入服务费" />
                        </el-form-item>
                    </el-col>
                </el-row>
                <!-- <el-row>
          <el-col :span="24">
            <el-form-item label="订单加价" prop="raiseAmount">
              <el-input-number v-model="form.raiseAmount" :precision="2" :step="100" placeholder="请输入订单加价" style="width:100%;" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="24">
            <el-form-item label="功能费" prop="functionAmount">
              <el-input-number v-model="form.functionAmount" :precision="2" :step="100" placeholder="请输入功能费" style="width:100%;" />
            </el-form-item>
          </el-col>
        </el-row>-->
                <!-- <el-row>
          <el-col :span="12">
            <el-form-item label="实付金额" prop="realMoney">
              <el-input-number v-model="form.realMoney" :precision="2" :step="100" placeholder="输入实付金额" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="实付金额备注" prop="remark">
              <el-input v-model="form.remark" type="textarea" :rows="3" placeholder="请输入内容" />
            </el-form-item>
          </el-col>
        </el-row> -->
                <el-row>
                    <el-col :span="12">
                        <!-- 修改实付金额表单项 -->
                        <el-form-item label="实付金额" prop="realMoney">
                            <el-input-number v-model="calculatedRealMoneyFromRemark" :precision="2" :step="100"
                                placeholder="自动计算实付金额" disabled :readonly="true" />
                        </el-form-item>
                    </el-col>
                    <el-col :span="12">
                        <el-form-item label="实付金额备注" prop="remark">
                            <el-input v-model="form.remark" type="textarea" :rows="3" placeholder="请输入内容"
                                @input="updateRealMoneyFromRemark" />
                        </el-form-item>
                    </el-col>
                </el-row>
                <el-row>
                    <el-col :span="12">
                        <el-form-item label="订单状态" prop="orderStatus">
                            <el-select v-model="form.orderStatus" placeholder="请选择订单状态" style="width: 100%;" disabled>
                                <el-option v-for="dict in orderStatusOptions" :key="dict.value" :label="dict.label"
                                    :value="dict.value">
                                </el-option>
                            </el-select>
                            <div v-if="previousOrderStatusAmount !== null && form.id" class="status-constraint-tip">
                                <i class="el-icon-info"></i>
                                <span>不可直接操作</span>
                                <p>由售后选择技术交付和客户确认</p>
                                <p>服务费,退单填写对应输入框后自动变化</p>
                            </div>
                        </el-form-item>
                    </el-col>
                    <el-col :span="12">
                        <el-form-item label="收款状态" prop="orderStatusAmount">
                            <el-select v-model="form.orderStatusAmount" placeholder="请选择订单收款状态" style="width: 100%;"
                                @change="handleOrderStatusAmountChange">
                                <el-option v-for="dict in filteredOrderStatusAmountOptions" :key="dict.value"
                                    :label="dict.label" :value="dict.value">
                                </el-option>
                            </el-select>
                            <div v-if="previousOrderStatusAmount !== null && form.id" class="status-constraint-tip">
                                <i class="el-icon-info"></i>
                                <span>当前只能选择"{{ getOrderStatusAmountLabel(previousOrderStatusAmount) }}"或以下的状态</span>
                                <div class="next-available-options">
                                    <span>可选项：</span>
                                    <el-tag v-for="option in filteredOrderStatusAmountOptions" :key="option.value"
                                        size="mini" type="info" style="margin-left: 5px;">
                                        {{ option.label }}
                                    </el-tag>
                                </div>
                            </div>
                        </el-form-item>
                    </el-col>
                </el-row>
                <el-row>
                    <el-col :span="12">
                        <el-form-item label="技术状态" prop="workStatus">
                            <el-select v-model="form.workStatus" placeholder="请选择技术状态" @change="handleWorkStatusChange">
                                <el-option v-for="dict in workStatusOptions" :key="dict.value" :label="dict.label"
                                    :value="dict.value"></el-option>
                            </el-select>
                        </el-form-item>
                    </el-col>
                </el-row>
                <el-row>
                    <el-col :span="12">
                        <el-form-item label="技术等级" prop="requiredSkillLevelId">
                            <el-select v-model="form.requiredSkillLevelId" placeholder="请选择所需最低技术等级" clearable>
                                <el-option v-for="level in skillLevelOptions" :key="level.value" :label="level.label"
                                    :value="level.value"></el-option>
                            </el-select>
                        </el-form-item>
                    </el-col>
                    <el-col :span="12">
                        <el-form-item label="信用分" prop="requiredCreditScore">
                            <el-select v-model="form.requiredCreditScore" placeholder="请选择所需最低信用分" clearable>
                                <el-option v-for="dict in creditScoreOptions" :key="dict.value" :label="dict.label"
                                    :value="dict.value"></el-option>
                            </el-select>
                        </el-form-item>
                    </el-col>
                </el-row>
                <el-row>
                    <el-col :span="12">
                        <el-form-item label="售中姓名" prop="inSaleId">
                            <el-select v-model="form.inSaleId" placeholder="请选择售中" style="width:100%;" clearable
                                filterable @change="handleInSaleChange">
                                <el-option v-for="user in inSaleUserOptions" :key="user.value" :label="user.label"
                                    :value="user.value" />
                            </el-select>
                        </el-form-item>
                    </el-col>
                    <el-col :span="12">
                        <el-form-item label="售后姓名" prop="afterSaleId">
                            <el-select v-model="form.afterSaleId" placeholder="请选择售后" style="width:100%;" clearable
                                filterable @change="handleAfterSaleChange">
                                <el-option v-for="user in afterSaleUserOptions" :key="user.value" :label="user.label"
                                    :value="user.value" />
                            </el-select>
                        </el-form-item>
                    </el-col>
                </el-row>
                <el-row>
                    <el-col :span="24">
                        <el-form-item label="技术" prop="acceptedProgrammerId">
                            <div v-for="(assignment, index) in programmerAssignments" :key="index"
                                style="margin-bottom: 10px;">
                                <el-row :gutter="10">
                                    <el-col :span="10">
                                        <el-select v-model="assignment.taskName" placeholder="请选择任务类型"
                                            style="width:100%;" clearable filterable>
                                            <el-option v-for="item in taskTypeOptions" :key="item.value"
                                                :label="item.label" :value="item.value" />
                                        </el-select>
                                    </el-col>
                                    <el-col :span="10">
                                        <el-select v-model="assignment.userId" placeholder="请选择技术" style="width:100%;"
                                            clearable filterable>
                                            <el-option v-for="user in programmerUserOptions" :key="user.value"
                                                :label="user.label" :value="user.value" />
                                        </el-select>
                                    </el-col>
                                    <el-col :span="3">
                                        <el-button type="danger" icon="el-icon-delete" circle
                                            @click="removeProgrammerAssignment(index)"></el-button>
                                    </el-col>
                                </el-row>
                            </div>
                            <el-button type="primary" icon="el-icon-plus"
                                @click="addProgrammerAssignment">添加技术人员</el-button>
                        </el-form-item>
                    </el-col>
                </el-row>
                <el-row>
                    <el-col :span="12">
                        <el-form-item label="接单时间" prop="acceptTime">
                            <el-date-picker clearable v-model="form.acceptTime" type="date" value-format="yyyy-MM-dd"
                                placeholder="请选择接单时间">
                            </el-date-picker>
                        </el-form-item>
                    </el-col>
                </el-row>
                <el-row>
                    <el-col :span="12">
                        <el-form-item label="交付物" prop="deliverable">
                            <el-input v-model="form.deliverable" type="textarea" placeholder="请输入内容" />
                        </el-form-item>
                    </el-col>
                    <el-col :span="12">
                        <el-form-item label="退单理由" prop="chargebackReason">
                            <el-input v-model="form.chargebackReason" type="textarea" placeholder="请输入退单理由" />
                        </el-form-item>
                    </el-col>
                </el-row>

                <el-row>
                    <el-col :span="24">
                        <el-form-item label="订单简介" prop="introduce">
                            <el-input v-model="form.introduce" type="textarea" :rows="3" placeholder="请输入订单简介内容" />
                        </el-form-item>
                    </el-col>
                </el-row>

                <el-row>
                    <el-col :span="24">
                        <el-form-item label="售后收款备注" prop="afterSalePaymentRemark">
                            <el-input v-model="form.afterSalePaymentRemark" type="textarea" :rows="3"
                                placeholder="请输入售后收款备注" />
                        </el-form-item>
                    </el-col>
                </el-row>

                <el-row>
                    <el-col :span="24">
                        <el-form-item label="售中进度" prop="inSaleProgress">
                            <el-input v-model="form.inSaleProgress" type="textarea" :rows="2"
                                placeholder="请输入售中进度信息" />
                        </el-form-item>
                    </el-col>
                </el-row>

                <el-row>
                    <el-col :span="24">
                        <el-form-item label="售后进度" prop="afterSaleProgress">
                            <el-input v-model="form.afterSaleProgress" type="textarea" :rows="2"
                                placeholder="请输入售后进度信息" />
                        </el-form-item>
                    </el-col>
                </el-row>

                <el-row v-if="form.receiptImages">
                    <el-col :span="24">
                        <el-form-item label="收款图片">
                            <div class="receipt-images-preview">
                                <div v-for="(image, index) in form.receiptImages.split(',')" :key="index"
                                    class="image-item">
                                    <el-image :src="image" :preview-src-list="form.receiptImages.split(',')" fit="cover"
                                        style="width: 80px; height: 80px; border-radius: 4px; margin-right: 10px;">
                                    </el-image>
                                </div>
                            </div>
                        </el-form-item>
                    </el-col>
                </el-row>

            </el-form>
            <div slot="footer" class="dialog-footer">
                <el-button type="primary" @click="submitForm">确 定</el-button>
                <el-button @click="cancel">取 消</el-button>
            </div>
        </el-dialog>

        <!-- 添加退款对话框 -->
        <el-dialog :title="refundTitle" :visible.sync="refundOpen" width="600px" append-to-body>
            <el-form ref="refundForm" :model="refundForm" :rules="refundRules" label-width="100px">
                <el-form-item label="退款金额" prop="refundAmount">
                    <el-input-number v-model="refundForm.refundAmount" :precision="2" :step="100"
                        placeholder="请输入退款金额" />
                </el-form-item>
                <el-form-item label="退款类型" prop="refundType">
                    <el-select v-model="refundForm.refundType" placeholder="请选择退款类型">
                        <el-option v-for="dict in refundTypeOptions" :key="dict.value" :label="dict.label"
                            :value="dict.value"></el-option>
                    </el-select>
                </el-form-item>
                <el-form-item label="退款原因" prop="refundReason">
                    <el-input v-model="refundForm.refundReason" type="textarea" placeholder="请输入退款原因" />
                </el-form-item>
                <!-- <el-form-item label="备注" prop="remark">
          <el-input v-model="refundForm.remark" type="textarea" placeholder="请输入备注" />
        </el-form-item> -->
            </el-form>
            <div slot="footer" class="dialog-footer">
                <el-button type="primary" @click="submitRefund">确 定</el-button>
                <el-button @click="cancelRefund">取 消</el-button>
            </div>
        </el-dialog>

        <!-- 文件上传对话框 -->
        <el-dialog :title="uploadTitle" :visible.sync="uploadOpen" width="500px" append-to-body>
            <el-form ref="uploadForm" :model="uploadForm" label-width="100px">
                <el-form-item label="需求文档">
                    <el-upload class="upload-demo" :action="uploadUrl" :headers="uploadHeaders"
                        :data="{ orderId: currentOrderId }" :on-success="handleRequirementSuccess"
                        :on-error="handleUploadError" :before-upload="beforeUpload" multiple :limit="5"
                        :file-list="requirementFileList">
                        <el-button size="small" type="primary">点击上传</el-button>
                        <div slot="tip" class="el-upload__tip">可上传多个文件，且不超过5个</div>
                    </el-upload>
                    <div v-if="requirementFiles.length > 0" class="file-list">
                        <h4>已上传的需求文档：</h4>
                        <ul>
                            <li v-for="file in requirementFiles" :key="file.fileId || file.url" class="file-item">
                                <a :href="file.url" target="_blank" class="file-link">{{ file.name }}</a>
                                <el-button v-if="file.fileId" size="mini" type="danger" icon="el-icon-delete"
                                    @click="handleDeleteRequirement(file)" class="delete-btn">删除</el-button>
                                <el-tag v-else size="mini" type="info" class="uploading-tag">上传中</el-tag>
                            </li>
                        </ul>
                    </div>
                </el-form-item>
                <el-form-item label="订单附件">
                    <el-upload class="upload-demo" :action="attachmentUploadUrl" :headers="uploadHeaders"
                        :data="{ orderId: currentOrderId }" :on-success="handleAttachmentSuccess"
                        :on-error="handleUploadError" :before-upload="beforeUpload" multiple :limit="5"
                        :file-list="attachmentFileList">
                        <el-button size="small" type="primary">点击上传</el-button>
                        <div slot="tip" class="el-upload__tip">可上传多个文件，且不超过5个</div>
                    </el-upload>
                    <div v-if="attachmentFiles.length > 0" class="file-list">
                        <h4>已上传的附件：</h4>
                        <ul>
                            <li v-for="file in attachmentFiles" :key="file.fileId || file.url" class="file-item">
                                <a :href="file.url" target="_blank" class="file-link">{{ file.name }}</a>
                                <el-button v-if="file.fileId" size="mini" type="danger" icon="el-icon-delete"
                                    @click="handleDeleteAttachment(file)" class="delete-btn">删除</el-button>
                                <el-tag v-else size="mini" type="info" class="uploading-tag">上传中</el-tag>
                            </li>
                        </ul>
                    </div>
                </el-form-item>
            </el-form>
            <div slot="footer" class="dialog-footer">
                <el-button @click="uploadOpen = false">取 消</el-button>
                <el-button type="primary" @click="submitUpload">确 定</el-button>
            </div>
        </el-dialog>

        <!-- 收款图片上传对话框 -->
        <el-dialog :title="receiptImageTitle" :visible.sync="receiptImageOpen" width="600px" append-to-body>
            <el-form ref="receiptImageForm" :model="receiptImageForm" label-width="100px">
                <el-form-item label="选择图片">
                    <el-upload class="upload-demo" :action="receiptImageUploadUrl" :headers="uploadHeaders"
                        :data="{ orderId: currentReceiptOrderId }" :on-success="handleReceiptImageSuccess"
                        :on-error="handleUploadError" :before-upload="beforeReceiptImageUpload" multiple :limit="10"
                        :file-list="receiptImageFileList" list-type="picture-card"
                        :on-preview="handlePictureCardPreview" :on-remove="handleRemove">
                        <i class="el-icon-plus"></i>
                    </el-upload>
                    <div slot="tip" class="el-upload__tip">只能上传jpg/png文件，且不超过10张</div>
                </el-form-item>
                <el-form-item label="已上传图片" v-if="currentReceiptImages">
                    <div class="receipt-images-preview">
                        <div v-for="(image, index) in currentReceiptImageList" :key="index" class="image-item">
                            <el-image :src="image" :preview-src-list="currentReceiptImageList" fit="cover"
                                style="width: 100px; height: 100px; border-radius: 4px;">
                            </el-image>
                            <span class="delete-icon" @click="handleDeleteReceiptImage(index)">
                                <i class="el-icon-delete"></i>
                            </span>
                        </div>
                    </div>
                </el-form-item>
            </el-form>
            <div slot="footer" class="dialog-footer">
                <el-button @click="receiptImageOpen = false">取 消</el-button>
                <el-button type="primary" @click="submitReceiptImages">确 定</el-button>
            </div>
        </el-dialog>

        <!-- 需求图片上传对话框 -->
        <el-dialog :title="demandImageTitle" :visible.sync="demandImageOpen" width="600px" append-to-body>
            <el-form ref="demandImageForm" :model="demandImageForm" label-width="100px">
                <el-form-item label="选择图片">
                    <el-upload class="upload-demo" :action="demandImageUploadUrl" :headers="uploadHeaders"
                        :data="{ orderId: currentDemandOrderId }" :on-success="handleDemandImageSuccess"
                        :on-error="handleUploadError" :before-upload="beforeDemandImageUpload" multiple :limit="10"
                        :file-list="demandImageFileList" list-type="picture-card"
                        :on-preview="handlePictureCardPreview" :on-remove="handleDemandImageRemove">
                        <i class="el-icon-plus"></i>
                    </el-upload>
                    <div slot="tip" class="el-upload__tip">只能上传jpg/png文件，且不超过10张</div>
                </el-form-item>
                <el-form-item label="已上传图片" v-if="currentDemandImages">
                    <div class="demand-images-preview">
                        <div v-for="(image, index) in currentDemandImageList" :key="index" class="image-item">
                            <el-image :src="image" :preview-src-list="currentDemandImageList" fit="cover"
                                style="width: 100px; height: 100px; border-radius: 4px;">
                            </el-image>
                            <span class="delete-icon" @click="handleDeleteDemandImage(index)">
                                <i class="el-icon-delete"></i>
                            </span>
                        </div>
                    </div>
                </el-form-item>
            </el-form>
            <div slot="footer" class="dialog-footer">
                <el-button @click="demandImageOpen = false">取 消</el-button>
                <el-button type="primary" @click="submitDemandImages">确 定</el-button>
            </div>
        </el-dialog>

        <!-- 发布任务对话框 -->
        <el-dialog :title="publishTaskTitle" :visible.sync="publishTaskOpen" width="600px" append-to-body>
            <el-form ref="publishTaskForm" :model="publishTaskForm" :rules="publishTaskRules" label-width="120px">
                <el-form-item label="订单号" prop="gradOrdersId">
                    <el-input v-model="publishTaskForm.orderNo" disabled />
                </el-form-item>
                <el-form-item label="订单任务类型" prop="gradOrdersTaskTypeId">
                    <el-select v-model="publishTaskForm.gradOrdersTaskTypeId" placeholder="请选择任务类型" style="width:100%;"
                        clearable filterable>
                        <el-option v-for="item in orderTaskTypes" :key="item.value" :label="item.label"
                            :value="item.value" />
                    </el-select>
                </el-form-item>
                <!-- <el-form-item label="指定程序员" prop="acceptedProgrammerId">
          <el-select v-model="publishTaskForm.acceptedProgrammerId" placeholder="请选择程序员" style="width:100%;" clearable filterable>
            <el-option v-for="user in programmerUserOptions" :key="user.value" :label="user.label" :value="user.value" />
          </el-select>
        </el-form-item> -->
                <!-- <el-form-item label="最终任务金额" prop="finalTaskAmount">
          <el-input-number v-model="publishTaskForm.finalTaskAmount" :precision="2" :step="100" placeholder="请输入最终任务金额" style="width:100%;" />
        </el-form-item> -->
                <!-- <el-form-item label="备注" prop="remark">
          <el-input v-model="publishTaskForm.remark" type="textarea" placeholder="请输入内容" />
        </el-form-item> -->
            </el-form>
            <div slot="footer" class="dialog-footer">
                <el-button type="primary" @click="submitPublishTaskForm">确 定</el-button>
                <el-button @click="cancelPublishTask">取 消</el-button>
            </div>
        </el-dialog>
    </div>
</template>

<script>
import { listOrders, getOrders, delOrders, addOrders, updateOrders, addRefund, listAllSkillLevels, listAllSkills, statistical, getOrderStatusCount, uploadReceiptImage, updateOrderStatusCloseSucceed, updateOrderStatusSucceed, switchCompletionStatus } from "@/api/dashboard/orders"
import { listOrderRequirements, listOrderAttachments } from "@/api/dashboard/orders"
import { approveSubmission, getSubmissions } from "@/api/dashboard/submissions";
import { listUsersByRoleName } from "@/api/system/user"
import { getToken } from "@/utils/auth"
import { listType } from "@/api/dashboard/type";
import { addTask } from "@/api/dashboard/task";
import { listOrderTaskTypes } from "@/api/dashboard/orders_task_type";
import { delRequirements } from "@/api/dashboard/requirements";
import { delAttachments } from "@/api/dashboard/attachments";
import request from "@/utils/request";
import { uploadFile } from "@/api/system/file";

export default {
    dicts: ['store'],
    name: "Orders",
    // 添加过滤器
    filters: {
        truncate(text, length) {
            if (!text) return '';
            if (text.length <= length) return text;
            return text.substring(0, length) + '...';
        }
    },
    data() {
        return {
            // 遮罩层
            loading: true,
            // 选中数组
            ids: [],
            // 非单个禁用
            single: true,
            // 非多个禁用
            multiple: true,
            // 显示搜索条件
            showSearch: true,
            // 总条数
            total: 0,
            // 订单主表表格数据
            ordersList: [],
            // 统计数据（由后端提供）
            statistics: {},
            // 是否有售后权限
            hasAfterSalePermission: false,
            // 弹出层标题
            title: "",
            // 是否显示弹出层
            open: false,
            // 备注时间范围
            daterangeStartTime: [],
            // 备注时间范围
            daterangeEstimatedEndTime: [],
            // 备注时间范围
            daterangeAcceptTime: [],
            beforeDate: null,
            maxRewardAmount: null,
            minRewardAmount: null,
            // 折叠面板展开项
            activeNames: [],
            // 查询参数
            queryParams: {
                pageNum: 1,
                pageSize: 10,
                orderNo: null,
                customerName: null,
                customerPhone: null,
                orderTitle: null,
                isUrgent: null,
                techTypes: null,
                startTime: null,
                estimatedEndTime: null,
                midPaymentTime: null,
                rewardAmount: null,
                raiseAmount: null,
                functionAmount: null,
                serviceCharge: null,  // 查询参数可以为null
                orderStatus: null,
                orderStatusAmount: null,
                inSaleName: null,
                afterSaleName: null,
                acceptedProgrammerName: null,
                acceptTime: null,
                chargebackReason: null,
                storeId: null,
                requiredCreditScore: null,
                requiredSkillLevelId: null,
                school: null,
                specialty: null,
                projectType: null,
                hardware: null,
                preSalesId: null,
                inSaleId: null,
                afterSaleId: null,
                acceptedProgrammerId: null,
                workStatus: null,
                orderByColumn: null,
                isAsc: null,
            },
            // 表单参数
            form: {
                id: null,
                orderNo: null,
                customerName: null,
                customerPhone: null,
                orderTitle: null,
                isUrgent: "0",
                // introduce: '客户编号:\n项目名称:\n开发语言:\n交付东西:\n交付日期:\n用途:\n旺旺名:\n店铺名称:\n电话:\n接单价格:\n已付价格:',
                introduce: null,
                techType: null,
                startTime: null,
                estimatedEndTime: null,
                midPaymentTime: null,
                rewardAmount: null,
                raiseAmount: null,
                functionAmount: null,
                serviceCharge: 0.00,  // 修改为 0.00，与其他金额字段一致
                preSalesAmount: 0.00,
                inSalesAmount: 0.00,
                afterSalesAmount: 0.00,
                orderStatus: "0",
                orderStatusAmount: "0",
                gradRefundId: null,
                preSalesId: null,
                inSaleId: null,
                afterSaleId: null,
                acceptedProgrammerId: null,
                acceptTime: null,
                chargebackReason: null,
                storeId: null,
                requiredCreditScore: null,
                requiredSkillLevelId: null,
                school: null,
                specialty: null,
                projectType: null,
                hardware: null,
                createBy: null,
                createTime: null,
                updateBy: null,
                updateTime: null,
                remark: '售前已收款( 0.00 )\n售中已收款( 0.00 )\n售后已收款( 0.00 )',
                submissionId: null,
                realMoney: 0.00,
                deliverable: null,
                beforeDate: null,
                maxRewardAmount: null,
                minRewardAmount: null,
                inSaleCollection1: 0.00,
                inSaleCollection2: 0.00,
                afterSaleCollected: 0.00,
                receiptImages: null,
                afterSalePaymentRemark: '项目名称: \n收款项: \n客户硬件费： \n新加功能费： \n项目技术： \n项目总价: \n硬件费： \n新加功能费： \n论文费： \n备注:  ',
                inSaleProgress: null,
                afterSaleProgress: null,

            },
            programmerAssignments: [],
            // 表单校验
            rules: {
                orderNo: [
                    { required: true, message: "订单号不能为空", trigger: "blur" }
                ],
                customerName: [
                    { required: true, message: "客户姓名不能为空", trigger: "blur" }
                ],
                customerPhone: [
                    { required: true, message: "客户联系方式不能为空", trigger: "blur" }
                ],
                orderTitle: [
                    { required: true, message: "订单标题不能为空", trigger: "blur" }
                ],
                isUrgent: [
                    { required: true, message: "是否加急订单不能为空", trigger: "change" }
                ],
                techType: [
                    { required: true, message: "程序类型不能为空", trigger: "change" }
                ],
                // startTime: [
                //   { required: true, message: "程序开始时间不能为空", trigger: "blur" }
                // ],
                workStatus: [
                    { required: true, message: "技术状态不能为空", trigger: "blur" }
                ],
                estimatedEndTime: [
                    { required: true, message: "截止时间不能为空", trigger: "blur" }
                ],
                rewardAmount: [
                    { required: true, message: "订单金额不能为空", trigger: "blur" }
                ],
                preSalesAmount: [
                    { required: true, message: "售前接单价不能为空", trigger: "blur" }
                ],
                // functionAmount: [
                //   { required: true, message: "功能费不能为空", trigger: "blur" }
                // ],
                // serviceCharge: [
                //   { required: true, message: "服务费记录不能为空", trigger: "blur" }
                // ],
                orderStatus: [
                    { required: true, message: "订单状态不能为空", trigger: "change" }
                ],
                orderStatusAmount: [
                    { required: true, message: "订单收款状态 不能为空", trigger: "change" },
                    { validator: this.validateOrderStatusAmount, trigger: "change" }
                ],
                // requiredCreditScore: [
                //   { required: true, message: "信用分不能为空", trigger: "change" }
                // ],
                // requiredSkillLevelId: [
                //   { required: true, message: "技术等级不能为空", trigger: "change" }
                // ],
                inSaleId: [
                    { validator: this.validateInSaleId, trigger: "change" }
                ],
                afterSaleId: [
                    { validator: this.validateAfterSaleId, trigger: "change" }
                ],
                acceptedProgrammerId: [
                    { validator: this.validateAcceptedProgrammerId, trigger: "change" }
                ],
            },
            // 文件上传相关
            uploadOpen: false,
            uploadTitle: "",
            uploadUrl: process.env.VUE_APP_BASE_API + "/dashboard/orders/requirement/upload",
            attachmentUploadUrl: process.env.VUE_APP_BASE_API + "/dashboard/orders/attachment/upload",
            requirementFileList: [],
            attachmentFileList: [],
            currentOrderId: null,
            uploadForm: {
                requirements: [],
                attachments: []
            },
            // 退款对话框
            refundOpen: false,
            refundTitle: "",
            currentRefundOrderId: null,
            currentRefundOrderNo: null,
            refundForm: {
                refundAmount: 0.00,
                refundType: null,
                refundReason: null,
                remark: null
            },
            refundRules: {
                refundAmount: [
                    { required: true, message: "退款金额不能为空", trigger: "blur" }
                ],
                refundType: [
                    { required: true, message: "退款类型不能为空", trigger: "change" }
                ],
                refundReason: [
                    { required: true, message: "退款原因不能为空", trigger: "blur" }
                ]
            },
            refundTypeOptions: [
                { label: '程序视频已发放', value: '0' },
                { label: '程序未做完', value: '1' },
                { label: '客户要求退款', value: '2' }
            ],
            requirementFiles: [],
            attachmentFiles: [],
            uploadHeaders: { Authorization: "Bearer " + getToken() },
            // 新增下拉框选项
            orderStatusOptions: [
                { label: '待抢单', value: '0' },
                { label: '重包单', value: '1' },
                { label: '进行中', value: '2' },
                { label: '未过售后期', value: '6' },
                { label: '已完成', value: '5' },
                { label: '服务费', value: '7' },
                { label: '已退单', value: '4' }
                // { label: '外部技术', value: '3' },
            ],
            orderStatusAmountOptions: [
                { label: '定金', value: '0' },
                { label: '首款', value: '1' },
                { label: '中期款', value: '2' },
                { label: '尾款', value: '3' },
                { label: '退款', value: '4' }
            ],
            isUrgentOptions: [
                { label: '加急', value: '1' },
                { label: '不加急', value: '0' }
            ],
            creditScoreOptions: [
                { label: '30', value: 30 }, // Numeric value for credit score
                { label: '50', value: 50 },
                { label: '60', value: 60 },
                { label: '80', value: 80 },
                { label: '100', value: 100 }
            ],
            skillLevelOptions: [],
            techTypeOptions: [],
            preSaleUserOptions: [],
            inSaleUserOptions: [],
            afterSaleUserOptions: [],
            techUserOptions: [],
            programmerUserOptions: [],
            taskTypeOptions: [],
            orderTaskTypes: [],
            projectTypeOptions: [
                { label: '毕业设计', value: '毕业设计' },
                { label: '个人项目', value: '个人项目' },
                { label: '商用项目', value: '商用项目' }
            ],
            workStatusOptions: [
                { label: '内部技术', value: '0' },
                { label: '外部技术', value: '1' }
            ],
            // 发布任务对话框
            publishTaskOpen: false,
            publishTaskTitle: "",
            publishTaskForm: {
                gradOrdersId: null,
                orderNo: null,
                gradOrdersTaskTypeId: null,
                acceptedProgrammerId: null,
                finalTaskAmount: 0.00,
                taskState: "0", // 默认为0，未中单
                remark: null
            },
            publishTaskRules: {
                gradOrdersId: [
                    { required: true, message: "订单号不能为空", trigger: "change" }
                ],
                gradOrdersTaskTypeId: [
                    { required: true, message: "订单任务类型不能为空", trigger: "change" }
                ],
                acceptedProgrammerId: [
                    { required: true, message: "指定程序员不能为空", trigger: "change" }
                ],
                finalTaskAmount: [
                    { required: true, message: "最终任务金额不能为空", trigger: "blur" }
                ]
            },
            // 收款图片上传相关
            receiptImageOpen: false,
            receiptImageTitle: "",
            receiptImageUploadUrl: process.env.VUE_APP_BASE_API + "/dashboard/orders/receipt-images/upload",
            receiptImageFileList: [],
            currentReceiptOrderId: null,
            currentReceiptOrderNo: null,
            currentReceiptImages: null,
            currentReceiptImageList: [],
            receiptImageForm: {},
            currentOrderForReceipt: {}, // 用于收款图操作时暂存订单数据
            // 需求图片上传相关
            demandImageOpen: false,
            demandImageTitle: "",
            demandImageUploadUrl: process.env.VUE_APP_BASE_API + "/dashboard/orders/demand-images/upload",
            demandImageFileList: [],
            currentDemandOrderId: null,
            currentDemandOrderNo: null,
            currentDemandImages: null,
            currentDemandImageList: [],
            demandImageForm: {},
            currentOrderForDemand: {}, // 用于需求图操作时暂存订单数据
            // 收款状态约束相关
            previousOrderStatusAmount: null,
            // 需求转订单时的临时需求简介，仅用于生成图片
            tempRequirementIntroduce: null,
            // 标识是否为需求转订单
            isFromSubmission: false,
        }
    },
    computed: {
        calculatedRealMoneyFromRemark() {
            return this.calculateRealMoneyFromRemarkText(this.form.remark);
        },
        // 过滤后的收款状态选项，只显示比上一次选择更大的值
        filteredOrderStatusAmountOptions() {
            // 如果是新增订单或者没有约束，显示所有选项
            if (this.previousOrderStatusAmount === null || !this.form.id) {
                return this.orderStatusAmountOptions;
            }

            // 编辑订单时，过滤出大于等于上一次选择的值（允许选择相同或更大的值）
            return this.orderStatusAmountOptions.filter(option => {
                const currentValue = parseInt(option.value);
                const previousValue = parseInt(this.previousOrderStatusAmount);
                return currentValue >= previousValue;
            });
        }
    },
    watch: {
        '$route': {
            handler(to, from) {
                const query = to.query;
                if (query && query.submissionId) {
                    this.handleAddFromSubmission(query);
                }
            },
            immediate: true // 立即执行，确保首次进入也生效
        },

    },
    created() {
        this.getList()
        this.getSkillLevels()
        this.getUserLists()
        this.gettechType()
        this.getTaskTypes()
        this.getOrderTaskTypes()
        this.checkAfterSalePermission()
    },
    methods: {
        tableRowClassName({ row }) {
            switch (row.orderStatus) {
                case '0': return 'row-pending';     // 待抢单 - 灰色
                case '1': return 'row-accepted';    // 重包单 - 浅绿色
                case '2': return 'row-processing';  // 进行中 - 蓝色
                case '4': return 'row-refunded';    // 已退单 - 黄色
                case '5': return 'row-completed';   // 已完成 - 红色
                case '6': return 'row-half';        // 半成品 - 紫色
                case '7': return 'row-service-fee'; // 服务费 - 橘色
                default: return '';
            }
        },
        /** 从提交记录跳转过来新增 */
        handleAddFromSubmission(query) {
            this.reset();
            this.isFromSubmission = true; // 标记为需求转订单

            getSubmissions(query.submissionId).then(response => {
                const row = response.data;
                this.open = true;
                this.title = "需求转订单";

                // 自动填充表单
                this.form.submissionId = query.submissionId;
                this.form.customerName = row.customerName;
                this.form.customerPhone = row.customerPhone;
                this.form.orderTitle = row.orderTitle;
                this.form.school = row.school;
                this.form.specialty = row.specialty;
                this.form.projectType = row.projectType;
                this.form.hardware = row.hardware;
                this.form.estimatedEndTime = row.estimatedEndTime;
                this.form.rewardAmount = row.rewardAmount;
                this.form.techType = row.techType;
                this.form.deliverable = query.deliverable || row.deliverable;

                // 将需求简介仅存储到临时变量，用于生成图片
                this.tempRequirementIntroduce = row.introduce;
                this.form.introduce = null; // 订单简介保持为空

                // 使用replace清除URL中的query参数，避免刷新时重复触发
                this.$router.replace({ path: '/dashboard/orders' });
            }).catch(() => {
                this.$modal.msgError("加载需求信息失败");
                this.$router.replace({ path: '/dashboard/orders' });
            });
        },
        /** 查询任务类型列表 */
        getTaskTypes() {
            listType({ pageNum: 1, pageSize: 999 }).then(response => {
                this.taskTypeOptions = response.rows.map(item => ({
                    value: item.orderTaskName,
                    label: item.orderTaskName
                }));
            });
        },
        /** 查询订单任务类型列表 */
        getOrderTaskTypes() {
            listOrderTaskTypes().then(response => {
                this.orderTaskTypes = response.rows.map(item => ({
                    value: item.id,
                    label: item.orderTaskName
                }));
            });
        },
        /** 查询技术等级列表 */
        getSkillLevels() {
            listAllSkillLevels().then(response => {
                this.skillLevelOptions = response.data.map(item => ({
                    value: item.id,
                    label: `${item.levelCode} - ${item.levelName}`
                }));
            });
        },
        /** 查询程序类型列表 */
        gettechType() {
            listAllSkills({ pageNum: 1, pageSize: 999 }).then(response => {
                this.techTypeOptions = response.rows.map(item => ({
                    value: item.name,
                    label: item.name
                }));
            });
        },
        getUserLists() {
            const formatUsers = (users) => {
                return users.map(user => ({
                    value: user.userId,
                    label: `${user.nickName} - ${user.phonenumber}`,
                    name: user.nickName
                }));
            };

            // 去重函数，根据userId去重
            const deduplicateUsers = (users) => {
                const userMap = new Map();
                users.forEach(user => {
                    userMap.set(user.userId, user);
                });
                return Array.from(userMap.values());
            };

            //   listUsersByRoleName("售前").then(response => {
            //     this.preSaleUserOptions = formatUsers(response.data);
            //   });
            //   listUsersByRoleName("售中").then(response => {
            //     this.inSaleUserOptions = formatUsers(response.data);
            //   });
            //   listUsersByRoleName("售后").then(response => {
            //     this.afterSaleUserOptions = formatUsers(response.data);
            //   });
            Promise.all([
                // 售前
                Promise.all([
                    listUsersByRoleName("售前"),
                    listUsersByRoleName("售前主管")
                ]).then(responses => {
                    const allPreSaleData = responses[0].data.concat(responses[1].data);
                    const uniquePreSaleData = deduplicateUsers(allPreSaleData);
                    this.preSaleUserOptions = formatUsers(uniquePreSaleData);
                }),

                // 售中
                Promise.all([
                    listUsersByRoleName("售中"),
                    listUsersByRoleName("售中主管")
                ]).then(responses => {
                    const allInSaleData = responses[0].data.concat(responses[1].data);
                    const uniqueInSaleData = deduplicateUsers(allInSaleData);
                    this.inSaleUserOptions = formatUsers(uniqueInSaleData);
                }),

                // 售后
                Promise.all([
                    listUsersByRoleName("售后"),
                    listUsersByRoleName("售后主管")
                ]).then(responses => {
                    const allAfterSaleData = responses[0].data.concat(responses[1].data);
                    const uniqueAfterSaleData = deduplicateUsers(allAfterSaleData);
                    this.afterSaleUserOptions = formatUsers(uniqueAfterSaleData);
                }),

                // 技术
                Promise.all([
                    listUsersByRoleName("公司技术"),
                    listUsersByRoleName("外包技术"),
                    listUsersByRoleName("写手")
                ]).then(responses => {
                    const allTechData = responses[0].data.concat(responses[1].data, responses[2].data);
                    const uniqueTechData = deduplicateUsers(allTechData);
                    this.techUserOptions = formatUsers(uniqueTechData);
                    // 程序员用户选项和技术用户选项相同
                    this.programmerUserOptions = formatUsers(uniqueTechData);
                })
            ]).then(() => {
                console.log("所有用户数据加载完成");
                // 这里可以执行所有数据加载完成后的操作
            }).catch(error => {
                console.error("加载用户数据时出错:", error);
            });

        },
        handleInSaleChange(userId) {
            if (!userId) {
                this.form.inSaleName = null;
                this.form.inSaleId = null;
            }
        },
        handleAfterSaleChange(userId) {
            if (!userId) {
                this.form.afterSaleName = null;
                this.form.afterSaleId = null;
            }
        },
        /** 技术状态切换处理 */
        handleWorkStatusChange(value) {
            console.log('=== 技术状态切换事件触发 ===');
            console.log('新技术状态值：', value);
            console.log('切换前订单状态：', this.form.orderStatus);

            // 使用 Vue.set 确保响应式更新
            this.$set(this.form, 'orderStatus', "0");

            console.log('切换后订单状态：', this.form.orderStatus);

            // 显示提示消息
            this.$message({
                type: 'success',
                message: `技术状态已切换为"${this.getWorkStatusLabel(value)}"，订单状态已自动设置为"待抢单"`,
                duration: 3000
            });

            // 技术状态切换后，重新验证相关字段
            this.$nextTick(() => {
                if (this.$refs.form) {
                    this.$refs.form.validateField('inSaleId');
                    this.$refs.form.validateField('afterSaleId');
                    this.$refs.form.validateField('acceptedProgrammerId');
                }
            });
        },

        /** 获取技术状态标签 */
        getWorkStatusLabel(value) {
            const option = this.workStatusOptions.find(opt => opt.value === value);
            return option ? option.label : value;
        },
        handleProgrammerChange(userIds) {
            if (!userIds || userIds.length === 0) {
                this.form.acceptedProgrammerName = null;
                this.form.acceptedProgrammerId = null;
            }
        },
        /** 查询订单主表列表 */
        getList() {
            this.loading = true
            this.queryParams.params = {}
            if (null != this.daterangeStartTime && '' != this.daterangeStartTime) {
                this.queryParams.params["beginStartTime"] = this.daterangeStartTime[0]
                this.queryParams.params["endStartTime"] = this.daterangeStartTime[1]
            }
            if (null != this.daterangeEstimatedEndTime && '' != this.daterangeEstimatedEndTime) {
                this.queryParams.params["beginEstimatedEndTime"] = this.daterangeEstimatedEndTime[0]
                this.queryParams.params["endEstimatedEndTime"] = this.daterangeEstimatedEndTime[1]
            }
            if (null != this.daterangeAcceptTime && '' != this.daterangeAcceptTime) {
                this.queryParams.params["beginAcceptTime"] = this.daterangeAcceptTime[0]
                this.queryParams.params["endAcceptTime"] = this.daterangeAcceptTime[1]
            }
            if (null != this.beforeDate && '' != this.beforeDate) {
                this.queryParams.params["beforeDate"] = this.beforeDate
            }
            if (null != this.minRewardAmount && '' != this.minRewardAmount) {
                this.queryParams.params["minRewardAmount"] = this.minRewardAmount
            }
            if (null != this.maxRewardAmount && '' != this.maxRewardAmount) {
                this.queryParams.params["maxRewardAmount"] = this.maxRewardAmount
            }
            
            // 确保排序字段包含id作为二级排序，避免分页数据重复
            if (this.queryParams.orderByColumn && !this.queryParams.orderByColumn.includes('id')) {
                this.queryParams.orderByColumn = `${this.queryParams.orderByColumn},id`;
                if (this.queryParams.isAsc) {
                    this.queryParams.isAsc = `${this.queryParams.isAsc},asc`;
                }
            }
            // 注释掉默认排序，让后端的订单状态优先级排序生效
            // else if (!this.queryParams.orderByColumn) {
            //     // 如果没有排序字段，默认按id排序
            //     this.queryParams.orderByColumn = 'id';
            //     this.queryParams.isAsc = 'desc';
            // }
            
            listOrders(this.queryParams).then(response => {
                this.ordersList = response.rows
                this.total = response.total
                this.loading = false

                // 计算页面利润差价（包单价格已通过SQL查询获取）
                this.calculateProfitDifference();
            });

            // 获取状态统计
            statistical(this.queryParams).then(response => {
                this.statistics = response.data;
            }).catch(error => {
                console.error('获取统计数据失败:', error);
                this.statistics = {};
            });
        },
        // 取消按钮
        cancel() {
            this.open = false
            this.reset()
        },
        // 表单重置
        // 表单重置
        reset() {
            this.form = {
                id: null,
                orderNo: null,
                customerName: null,
                customerPhone: null,
                orderTitle: null,
                isUrgent: "0",
                // introduce: '客户编号:\n项目名称:\n开发语言:\n交付东西:\n交付日期:\n用途:\n旺旺名:\n店铺名称:\n电话:\n接单价格:\n已付价格:',
                introduce: null,
                techType: null,
                startTime: null,
                estimatedEndTime: null,
                midPaymentTime: null,
                rewardAmount: null,
                raiseAmount: null,
                functionAmount: null,
                serviceCharge: 0.00,  // 修改为 0.00，与其他金额字段一致
                preSalesAmount: 0.00,
                inSalesAmount: 0.00,
                afterSalesAmount: 0.00,
                orderStatus: "0",
                orderStatusAmount: "0",
                gradRefundId: null,
                preSalesId: null,
                inSaleId: null,
                afterSaleId: null,
                acceptedProgrammerId: null,
                acceptTime: null,
                chargebackReason: null,
                storeId: null,
                requiredCreditScore: null,
                requiredSkillLevelId: null,
                school: null,
                specialty: null,
                projectType: null,
                hardware: null,
                createBy: null,
                createTime: null,
                updateBy: null,
                updateTime: null,
                remark: '售前已收款( 0.00 )\n售中已收款( 0.00 )\n售后已收款( 0.00 )',
                submissionId: null,
                realMoney: 0.00,
                deliverable: null,
                beforeDate: null,
                maxRewardAmount: null,
                minRewardAmount: null,
                inSaleCollection1: 0.00,
                inSaleCollection2: 0.00,
                afterSaleCollected: 0.00,
                receiptImages: null,
                afterSalePaymentRemark: '项目名称: \n收款项: \n客户硬件费： \n新加功能费： \n项目技术： \n项目总价: \n硬件费： \n新加功能费： \n论文费： \n备注:  ',
                inSaleProgress: null,
                afterSaleProgress: null,
            }
            this.resetForm("form")
            // 重置收款状态约束
            this.previousOrderStatusAmount = null;
            // 重置需求转订单相关状态
            this.tempRequirementIntroduce = null;
            this.isFromSubmission = false;
        },
        /** 搜索按钮操作 */
        handleQuery() {
            this.queryParams.pageNum = 1
            this.getList()
        },
        /** 重置按钮操作 */
        resetQuery() {
            this.maxRewardAmount = null;
            this.minRewardAmount = null;
            this.beforeDate = null; // 重置 beforeDate
            this.queryParams.params = {}; // 清空 params
            this.queryParams.orderByColumn = null; // 重置排序字段
            this.queryParams.isAsc = null; // 重置排序方向
            this.daterangeStartTime = []; // 重置接单时间范围
            this.daterangeEstimatedEndTime = []; // 重置截止时间范围
            this.daterangeAcceptTime = []; // 重置接单时间范围
            this.resetForm("queryForm"); // 重置表单
            this.resetForm("quickFilterForm"); // 重置快速筛选表单
            this.handleQuery(); // 重新查询
        },
        // 多选框选中数据
        handleSelectionChange(selection) {
            this.ids = selection.map(item => item.id)
            this.single = selection.length !== 1
            this.multiple = !selection.length
        },
        /** 新增按钮操作 */
        handleAdd() {
            this.reset()
            // 新增订单时重置收款状态约束
            this.previousOrderStatusAmount = null;
            this.open = true
            this.title = "新增订单"
        },

        // 从备注文本中提取金额并计算总和
        calculateRealMoneyFromRemarkText(remarkText) {
            if (!remarkText) return 0.00;
            console.log("remarkText:", remarkText);
            let total = 0;
            const lines = remarkText.split('\n');
            console.log("lines:", lines);

            lines.forEach(line => {
                // 使用正则表达式匹配 "收款(X)" 格式，其中X是数字
                const match = line.match(/已收款\s*\(\s*(\d+(?:\.\d+)?)\s*\)/);
                if (match) {
                    total += parseFloat(match[1]) || 0;
                }
            });
            console.log("total:", total);
            console.log("计算方法得到的值：", parseFloat(total.toFixed(2)))
            return parseFloat(total.toFixed(2));
        },

        // 当备注文本改变时更新实付金额
        updateRealMoneyFromRemark() {
            this.form.realMoney = this.calculatedRealMoneyFromRemark;
        },

        // 计算订单总金额
        calculateTotalAmount() {
            const preSales = this.form.preSalesAmount || 0;
            const inSales = this.form.inSalesAmount || 0;
            const afterSales = this.form.afterSalesAmount || 0;
            this.form.rewardAmount = parseFloat((preSales + inSales + afterSales).toFixed(2));
        },

        // 计算页面利润差价（包单价格已通过SQL查询获取）
        calculateProfitDifference() {
            if (!this.ordersList || this.ordersList.length === 0) {
                return;
            }

            // 计算当前页面的利润差价
            this.ordersList.forEach(order => {
                const packageAmount = parseFloat(order.packageAmount) || 0;
                const rewardAmount = parseFloat(order.rewardAmount) || 0;
                const serviceCharge = parseFloat(order.serviceCharge) || 0;

                // 确保包单价格格式正确
                this.$set(order, 'packageAmount', packageAmount.toFixed(2));

                // 计算利润差价：如果服务费不等于0，则利润差价为服务费；否则为订单总价 - 包单价格
                let profitDifference;
                if (serviceCharge !== 0) {
                    profitDifference = serviceCharge;
                } else {
                    profitDifference = rewardAmount - packageAmount;
                }
                this.$set(order, 'profitDifference', profitDifference.toFixed(2));
            });
        },

        /** 修改按钮操作 */
        handleUpdate(row) {
            this.reset()
            const id = row.id || this.ids
            getOrders(id).then(response => {
                this.form = response.data
                // 确保数值字段有默认值
                this.form.inSaleCollection1 = response.data.inSaleCollection1 !== undefined ?
                    parseFloat(response.data.inSaleCollection1) : 0.00;
                this.form.inSaleCollection2 = response.data.inSaleCollection2 !== undefined ?
                    parseFloat(response.data.inSaleCollection2) : 0.00;
                this.form.afterSaleCollected = response.data.afterSaleCollected !== undefined ?
                    parseFloat(response.data.afterSaleCollected) : 0.00;

                // 确保新字段有默认值
                this.form.preSalesAmount = response.data.preSalesAmount !== undefined ?
                    parseFloat(response.data.preSalesAmount) : 0.00;
                this.form.inSalesAmount = response.data.inSalesAmount !== undefined ?
                    parseFloat(response.data.inSalesAmount) : 0.00;
                this.form.afterSalesAmount = response.data.afterSalesAmount !== undefined ?
                    parseFloat(response.data.afterSalesAmount) : 0.00;
                
                // 确保服务费字段有默认值
                this.form.serviceCharge = response.data.serviceCharge !== undefined && response.data.serviceCharge !== null ?
                    parseFloat(response.data.serviceCharge) : 0.00;

                // if (!this.form.introduce) {
                //     this.form.introduce = '客户编号:\n项目名称:\n开发语言:\n交付东西:\n交付日期:\n用途:\n旺旺名:\n店铺名称:\n电话:\n接单价格:\n已付价格:';
                // }

                // 如果没有 remark 字段或者为空，设置默认值
                if (!this.form.remark) {
                    this.form.remark = '售前已收款( 0 )\n售中已收款( 0 )\n售后已收款( 0 )';
                }

                // 如果没有 afterSalePaymentRemark 字段或者为空，设置默认值
                if (!this.form.afterSalePaymentRemark) {
                    this.form.afterSalePaymentRemark = '项目名称: \n收款项: \n客户硬件费： \n新加功能费： \n项目技术： \n项目总价: \n硬件费： \n新加功能费： \n论文费： \n备注:  ';
                }

                // 如果没有 inSaleProgress 字段，设置默认值
                if (!this.form.inSaleProgress) {
                    this.form.inSaleProgress = null;
                }

                // 如果没有 afterSaleProgress 字段，设置默认值
                if (!this.form.afterSaleProgress) {
                    this.form.afterSaleProgress = null;
                }

                // 根据备注内容更新实付金额
                // 立即计算实付金额和订单总金额
                this.$nextTick(() => {
                    this.form.realMoney = this.calculatedRealMoneyFromRemark;
                    this.calculateTotalAmount();
                });

                // 初始化收款状态约束
                this.previousOrderStatusAmount = this.form.orderStatusAmount;

                this.programmerAssignments = [];
                if (this.form.acceptedProgrammerId && typeof this.form.acceptedProgrammerId === 'string') {
                    const assignments = this.form.acceptedProgrammerId.split(',');
                    assignments.forEach(a => {
                        const parts = a.trim().split('-');
                        if (parts.length === 2) {
                            const userId = parseInt(parts[1], 10);
                            if (!isNaN(userId)) {
                                this.programmerAssignments.push({ taskName: parts[0].trim(), userId: userId });
                            }
                        } else {
                            // 兼容旧格式，只有id
                            const userId = parseInt(a.trim(), 10);
                            if (!isNaN(userId)) {
                                this.programmerAssignments.push({ taskName: null, userId: userId });
                            }
                        }
                    });
                }
                if (this.programmerAssignments.length === 0) {
                    this.addProgrammerAssignment();
                }
                this.open = true
                this.title = "修改订单主表"
            })
        },
        /** 提交按钮 */
        async submitForm() {
            this.$refs["form"].validate(async (valid) => {
                if (valid) {
                    let loading = null;
                    try {
                        // 显示加载状态
                        loading = this.$loading({
                            lock: true,
                            text: '正在保存订单...',
                            spinner: 'el-icon-loading',
                            background: 'rgba(0, 0, 0, 0.7)'
                        });

                        const assignments = this.programmerAssignments
                            .map(a => {
                                if (a.taskName && a.userId) {
                                    return `${a.taskName}-${a.userId}`;
                                }
                                return null;
                            })
                            .filter(a => a !== null);

                        const dataToSubmit = { ...this.form };
                        dataToSubmit.acceptedProgrammerId = assignments.join(',');
                        dataToSubmit.realMoney = this.calculatedRealMoneyFromRemark;
                        
                        // 确保服务费字段正确处理：0值也要发送，不能是undefined
                        if (dataToSubmit.serviceCharge === null || dataToSubmit.serviceCharge === undefined || dataToSubmit.serviceCharge === '') {
                            dataToSubmit.serviceCharge = 0.00;
                        }

                        const submissionId = dataToSubmit.submissionId;
                        if (submissionId) {
                            delete dataToSubmit.submissionId;
                        }

                        // 如果是需求转订单，确保不存储需求简介到订单简介
                        if (this.isFromSubmission) {
                            dataToSubmit.introduce = null;
                        }

                        // 如果有需求简介，先生成并上传图片，然后将路径添加到demandUrl
                        if (this.tempRequirementIntroduce) {
                            try {
                                loading.text = '正在生成需求图片...';
                                console.log('开始生成需求图片');
                                console.log('需求简介内容:', this.tempRequirementIntroduce);
                                console.log('订单数据:', dataToSubmit);

                                // 生成图片
                                const imageBlob = await this.generateRequirementImage(dataToSubmit);
                                console.log('图片生成成功，大小:', imageBlob.size, 'bytes');

                                loading.text = '正在上传需求图片...';

                                // 上传图片到通用文件接口
                                const imageUrl = await this.uploadGeneratedImage(imageBlob);
                                console.log('图片上传成功，返回URL:', imageUrl);

                                // 将图片URL添加到demandUrl字段
                                const currentDemandUrl = dataToSubmit.demandUrl || '';
                                const newDemandUrl = currentDemandUrl ? `${currentDemandUrl},${imageUrl}` : imageUrl;
                                dataToSubmit.demandUrl = newDemandUrl;
                                console.log('已将图片URL添加到demandUrl:', newDemandUrl);

                            } catch (imageError) {
                                console.error('生成或上传需求图片失败:', imageError);
                                if (loading) loading.close();
                                this.$modal.msgError(`需求图片生成失败: ${imageError.message}，请重试`);
                                return;
                            }
                        }

                        loading.text = '正在保存订单...';

                        let response;
                        if (dataToSubmit.id != null) {
                            response = await updateOrders(dataToSubmit);
                        } else {
                            response = await addOrders(dataToSubmit);
                        }

                        console.log('API响应结构:', response);

                        // 根据实际API响应结构获取订单ID
                        let orderId;
                        if (dataToSubmit.id != null) {
                            // 更新操作，使用原有ID
                            orderId = dataToSubmit.id;
                        } else {
                            // 新增操作，尝试从响应中获取ID
                            orderId = response?.data?.id || response?.id || response?.data;

                            // 如果响应中没有ID，尝试通过订单号查询获取ID
                            if (!orderId && dataToSubmit.orderNo) {
                                console.log('响应中没有ID，尝试通过订单号查询获取ID...');
                                try {
                                    // 通过订单号查询获取订单信息
                                    const queryResponse = await listOrders({
                                        pageNum: 1,
                                        pageSize: 1,
                                        orderNo: dataToSubmit.orderNo
                                    });

                                    if (queryResponse.rows && queryResponse.rows.length > 0) {
                                        orderId = queryResponse.rows[0].id;
                                        console.log('通过订单号查询获取到ID:', orderId);
                                    }
                                } catch (queryError) {
                                    console.error('通过订单号查询ID失败:', queryError);
                                }
                            }

                            if (!orderId) {
                                console.warn('无法获取新创建的订单ID，将跳过图片生成。响应:', response);
                            }
                        }


                        if (loading) loading.close();
                        this.$modal.msgSuccess(dataToSubmit.id ? "修改成功" : "新增成功");

                        this.open = false;

                        if (submissionId) {
                            approveSubmission(submissionId).then(() => {
                                this.$modal.msgSuccess("订单创建成功，提交记录已自动审核通过！");
                            });
                        }

                        this.getList();

                    } catch (error) {
                        if (loading) loading.close();
                        console.error('提交表单错误:', error);
                        this.$modal.msgError("操作失败: " + (error.message || "未知错误"));
                    }
                }
            });
        },
        /** 删除按钮操作 */
        handleDelete(row) {
            const ids = row.id || this.ids
            this.$modal.confirm('是否确认删除订单主表编号为"' + ids + '"的数据项？').then(function () {
                return delOrders(ids)
            }).then(() => {
                this.getList()
                this.$modal.msgSuccess("删除成功")
            }).catch(() => { })
        },
        /** 导出按钮操作 */
        handleExport() {
            this.download('dashboard/orders/export', {
                ...this.queryParams
            }, `orders_${new Date().getTime()}.xlsx`)
        },
        /** 排序操作 */
        handleSort(command) {
            const [column, order] = command.split('.');
            // 添加id作为二级排序，避免分页重复
            this.queryParams.orderByColumn = `${column},id`;
            this.queryParams.isAsc = `${order},asc`;
            this.handleQuery();
        },
        /** 退款按钮操作 */
        handleRefund(row) {
            this.currentRefundOrderId = row.id;
            this.currentRefundOrderNo = row.orderNo;
            this.refundOpen = true;
            this.refundTitle = "订单退款 - " + row.orderNo;
            this.$nextTick(() => {
                if (this.$refs.refundForm) {
                    this.$refs.refundForm.resetFields();
                }
            });
        },
        // 取消退款按钮
        cancelRefund() {
            this.refundOpen = false;
        },
        /** 提交退款按钮 */
        submitRefund() {
            this.$refs["refundForm"].validate(valid => {
                if (valid) {
                    const refundData = {
                        ...this.refundForm,
                        orderId: this.currentRefundOrderId,
                        orderNo: this.currentRefundOrderNo
                    };
                    addRefund(refundData).then(response => {
                        this.$modal.msgSuccess("新增退款成功");
                        this.refundOpen = false;
                        this.getList();
                    });
                }
            });
        },
        /** 文件上传按钮操作 */
        handleUpload(row) {
            this.currentOrderId = row.id;
            this.uploadTitle = "上传文件 - " + row.orderNo;
            this.uploadOpen = true;
            this.requirementFileList = [];
            this.attachmentFileList = [];
            this.uploadForm = {
                requirements: [],
                attachments: []
            };

            // 获取已上传的文件列表
            this.getFileLists();
        },

        /** 获取文件列表 */
        getFileLists() {
            // 获取需求文档列表
            listOrderRequirements(this.currentOrderId).then(response => {
                if (response.code === 200) {
                    this.requirementFiles = response.data;
                }
            });

            // 获取附件列表
            listOrderAttachments(this.currentOrderId).then(response => {
                if (response.code === 200) {
                    this.attachmentFiles = response.data;
                }
            });
        },

        /** 需求文档上传成功处理 */
        handleRequirementSuccess(response, file, fileList) {
            if (response.code === 200) {
                this.uploadForm.requirements.push({
                    orderId: this.currentOrderId,
                    fileName: response.data.name,
                    fileUrl: response.data.url,
                    fileType: 'requirement'
                });
                this.requirementFiles.push(response.data);
                this.$modal.msgSuccess("需求文档上传成功");
            } else {
                this.$modal.msgError(response.msg || "需求文档上传失败，请稍后再试");
            }
        },

        /** 附件上传成功处理 */
        handleAttachmentSuccess(response, file, fileList) {
            if (response.code === 200) {
                this.uploadForm.attachments.push({
                    orderId: this.currentOrderId,
                    fileName: response.data.name,
                    fileUrl: response.data.url,
                    fileType: 'attachment'
                });
                this.attachmentFiles.push(response.data);
                this.$modal.msgSuccess("附件上传成功");
            } else {
                this.$modal.msgError(response.msg || "附件上传失败，请稍后再试");
            }
        },

        /** 上传失败处理 */
        handleUploadError(err) {
            const errorMsg = err.message || "文件上传失败，请检查网络或联系管理员";
            this.$modal.msgError(errorMsg);
        },

        /** 上传前校验 */
        beforeUpload(file) {
            const isLt100M = file.size / 1024 / 1024 < 100;
            // if (!isLt100M) {
            //   this.$message.error('上传文件大小不能超过 100MB!');
            //   return false;
            // }
            return true;
        },

        /** 提交上传 */
        submitUpload() {
            this.uploadOpen = false;
            this.$modal.msgSuccess("文件操作完成");
        },

        /** 删除需求文档 */
        handleDeleteRequirement(file) {
            this.$modal.confirm(`确认删除需求文档"${file.name}"吗？`).then(() => {
                if (!file.fileId) {
                    this.$modal.msgError("无法获取文件ID，删除失败");
                    return;
                }
                delRequirements(file.fileId).then(response => {
                    this.$modal.msgSuccess("删除成功");
                    // 刷新需求文档列表
                    this.getFileLists();
                }).catch(error => {
                    this.$modal.msgError("删除失败：" + (error.message || "未知错误"));
                });
            }).catch(() => {
                this.$modal.msgInfo("已取消删除");
            });
        },

        /** 删除订单附件 */
        handleDeleteAttachment(file) {
            this.$modal.confirm(`确认删除附件"${file.name}"吗？`).then(() => {
                if (!file.fileId) {
                    this.$modal.msgError("无法获取文件ID，删除失败");
                    return;
                }
                delAttachments(file.fileId).then(response => {
                    this.$modal.msgSuccess("删除成功");
                    // 刷新附件列表
                    this.getFileLists();
                }).catch(error => {
                    this.$modal.msgError("删除失败：" + (error.message || "未知错误"));
                });
            }).catch(() => {
                this.$modal.msgInfo("已取消删除");
            });
        },
        /** 发布任务按钮操作 */
        handlePublishTask(row) {
            this.resetPublishTaskForm();
            this.publishTaskOpen = true;
            this.publishTaskTitle = "发布任务 - " + row.orderNo;
            this.publishTaskForm.gradOrdersId = row.id;
            this.publishTaskForm.orderNo = row.orderNo;
        },
        /** 转换字典标签 */
        selectDictLabel(datas, value) {
            if (value === undefined || value === null || value === '') {
                return "";
            }
            const actions = [];
            Object.keys(datas).map((key) => {
                if (datas[key].value == ('' + value)) {
                    actions.push(datas[key].label);
                    return false;
                }
            })
            return actions.join('');
        },
        getStatusTag(status) {
            const statusColors = {
                '1': '#409eff',    // 重包单 -> blue
                '2': '#409eff',    // 进行中 -> blue
                '4': '#e6a23c',    // 已退单 -> yellow
                '5': '#f56c6c',    // 已完成 -> red
                '6': '#673ab7',    // 半成品 -> purple
                '7': '#67c23a',    // 服务费 -> green
            };
            // For other statuses like '待抢单' (0), use the default info color
            return statusColors[status] || '#909399';
        },
        tableCellClassName({ row, column, rowIndex, columnIndex }) {
            if (column.property === 'orderStatus') {
                switch (row.orderStatus) {
                    case '1': return 'status-cell-blue'; // 重包单
                    case '4': return 'status-cell-yellow'; // 已退单
                    case '5': return 'status-cell-red'; // 已完成
                    case '6': return 'status-cell-purple'; // 半成品
                    case '7': return 'status-cell-green'; // 服务费
                    default: return '';
                }
            }
            return '';
        },
        /** 订单状态字典翻译 */
        orderStatusFormat(row, column) {
            // ... existing code ...
        },
        addProgrammerAssignment() {
            this.programmerAssignments.push({ taskName: null, userId: null });
        },
        removeProgrammerAssignment(index) {
            this.programmerAssignments.splice(index, 1);
        },
        // 发布任务表单重置
        resetPublishTaskForm() {
            this.publishTaskForm = {
                gradOrdersId: null,
                orderNo: null,
                gradOrdersTaskTypeId: null,
                acceptedProgrammerId: null,
                finalTaskAmount: 0.00,
                taskState: "0", // 默认为0，未中单
                remark: null
            };
            this.resetForm("publishTaskForm");
        },
        /** 提交发布任务表单 */
        submitPublishTaskForm() {
            this.$refs["publishTaskForm"].validate(valid => {
                if (valid) {
                    addTask(this.publishTaskForm).then(response => {
                        this.$modal.msgSuccess("任务发布成功");
                        this.publishTaskOpen = false;
                        this.getList();
                    }).catch(() => { });
                }
            });
        },
        // 取消发布任务按钮
        cancelPublishTask() {
            this.publishTaskOpen = false;
            this.resetPublishTaskForm();
        },
        /** 收款图片按钮操作 */
        handleReceiptImages(row) {
            this.currentOrderForReceipt = { ...row }; // 暂存订单数据
            this.currentReceiptOrderId = row.id;
            this.currentReceiptOrderNo = row.orderNo;
            this.currentReceiptImages = row.receiptImages;
            this.currentReceiptImageList = row.receiptImages ? row.receiptImages.split(',') : [];
            this.receiptImageOpen = true;
            this.receiptImageTitle = "上传收款图片 - " + row.orderNo;
            this.receiptImageFileList = [];
            this.receiptImageForm = {};
        },

        /** 收款图片上传成功处理 */
        handleReceiptImageSuccess(response, file, fileList) {
            if (response.code === 200) {
                this.$modal.msgSuccess("收款图片上传成功");
                this.getList(); // 刷新列表数据
            } else {
                this.$modal.msgError(response.msg || "收款图片上传失败，请稍后再试");
            }
        },

        /** 处理收款状态变化 */
        handleOrderStatusAmountChange(value) {
            if (value === '4') { // '4' is for '退款'
                this.$modal.confirm('确认将收款状态修改为"退款"吗？此操作将相应更新订单状态。').then(() => {
                    // User confirmed. The value is already changed by v-model.
                    // We just need to update our tracker for the "previous" value for subsequent changes.
                    if (value !== null && value !== undefined) {
                        this.previousOrderStatusAmount = value;
                    }
                }).catch(() => {
                    // User canceled. Revert the value.
                    this.$nextTick(() => {
                        this.form.orderStatusAmount = this.previousOrderStatusAmount;
                    });
                });
            } else {
                // For any other status, just update the previous value tracker.
                if (value !== null && value !== undefined) {
                    this.previousOrderStatusAmount = value;
                }
            }
        },

        /** 获取收款状态标签 */
        getOrderStatusAmountLabel(value) {
            const option = this.orderStatusAmountOptions.find(opt => opt.value === value);
            return option ? option.label : '';
        },

        /** 验证收款状态选择 */
        validateOrderStatusAmount(rule, value, callback) {
            // 只在编辑订单且有约束时进行验证
            if (this.previousOrderStatusAmount !== null && value !== null && this.form.id) {
                const currentValue = parseInt(value);
                const previousValue = parseInt(this.previousOrderStatusAmount);

                if (currentValue < previousValue) {
                    callback(new Error(`收款状态不能比"${this.getOrderStatusAmountLabel(this.previousOrderStatusAmount)}"更小`));
                    return;
                }
            }
            callback();
        },

        /** 验证售中姓名 - 外部技术时必填 */
        validateInSaleId(rule, value, callback) {
            if (this.form.workStatus === '1' && (!value || value === '')) {
                callback(new Error('外部技术时售中姓名为必填项'));
                return;
            }
            callback();
        },

        /** 验证售后姓名 - 内部技术时必填 */
        validateAfterSaleId(rule, value, callback) {
            if (this.form.workStatus === '0' && (!value || value === '')) {
                callback(new Error('内部技术时售后姓名为必填项'));
                return;
            }
            callback();
        },

        /** 验证技术人员 - 内部技术时必填 */
        validateAcceptedProgrammerId(rule, value, callback) {
            if (this.form.workStatus === '0') {
                // 检查是否有技术人员分配
                const hasValidAssignment = this.programmerAssignments &&
                    this.programmerAssignments.some(assignment => assignment.userId);

                if (!hasValidAssignment) {
                    callback(new Error('内部技术时技术人员为必填项'));
                    return;
                }
            }
            callback();
        },

        /** 收款图片上传前校验 */
        beforeReceiptImageUpload(file) {
            const isImage = file.type.indexOf('image/') === 0;
            const isLt5M = file.size / 1024 / 1024 < 5;

            if (!isImage) {
                this.$message.error('只能上传图片文件!');
                return false;
            }
            if (!isLt5M) {
                this.$message.error('上传图片大小不能超过 5MB!');
                return false;
            }
            return true;
        },

        /** 图片预览 */
        handlePictureCardPreview(file) {
            this.dialogImageUrl = file.url;
            this.dialogVisible = true;
        },

        /** 移除图片 */
        handleRemove(file, fileList) {
            // 处理移除图片的逻辑
        },

        /** 提交收款图片 */
        submitReceiptImages() {
            this.receiptImageOpen = false;
            this.$modal.msgSuccess("收款图片操作完成");
        },

        /** 需求图片按钮操作 */
        handleDemandImages(row) {
            this.currentOrderForDemand = { ...row }; // 暂存订单数据，用于删除操作
            this.currentDemandOrderId = row.id;
            this.currentDemandOrderNo = row.orderNo;
            this.currentDemandImages = row.demandUrl;
            this.currentDemandImageList = row.demandUrl ? row.demandUrl.split(',') : [];
            this.demandImageOpen = true;
            this.demandImageTitle = "上传需求图片 - " + row.orderNo;
            this.demandImageFileList = [];
            this.demandImageForm = {};
        },

        /** 需求图片上传成功处理 */
        handleDemandImageSuccess(response, file, fileList) {
            if (response.code === 200) {
                this.$modal.msgSuccess("需求图片上传成功");
                this.getList(); // 刷新列表数据
            } else {
                this.$modal.msgError(response.msg || "需求图片上传失败，请稍后再试");
            }
        },

        /** 需求图片上传前校验 */
        beforeDemandImageUpload(file) {
            const isImage = file.type.indexOf('image/') === 0;
            const isLt5M = file.size / 1024 / 1024 < 5;

            if (!isImage) {
                this.$message.error('只能上传图片文件!');
                return false;
            }
            if (!isLt5M) {
                this.$message.error('上传图片大小不能超过 5MB!');
                return false;
            }
            return true;
        },

        /** 移除需求图片 */
        handleDemandImageRemove(file, fileList) {
            // 处理移除需求图片的逻辑
        },

        /** 删除需求图片 */
        handleDeleteDemandImage(index) {
            this.$modal.confirm('确认删除这张需求图片吗？').then(() => {
                const images = [...this.currentDemandImageList];
                images.splice(index, 1);
                const newDemandImagesString = images.join(',');

                // 拷贝暂存的订单数据，以保留其他字段信息
                const payload = { ...this.currentOrderForDemand };
                // 更新需求图片
                payload.demandUrl = newDemandImagesString;

                updateOrders(payload).then(response => {
                    this.$modal.msgSuccess("删除成功");
                    this.currentDemandImages = newDemandImagesString;
                    this.currentDemandImageList = images;
                    this.getList(); // 刷新列表数据
                }).catch(() => {
                    this.$modal.msgError("删除失败");
                });
            }).catch(() => {
                this.$modal.msgInfo("已取消删除");
            });
        },

        /** 提交需求图片 */
        submitDemandImages() {
            this.demandImageOpen = false;
            this.$modal.msgSuccess("需求图片操作完成");
        },

        /** 删除收款图片操作 */
        handleDeleteReceiptImage(index) {
            this.$modal.confirm('是否确认删除该收款图片？').then(() => {
                const images = [...this.currentReceiptImageList];
                images.splice(index, 1);
                const newReceiptImagesString = images.join(',');

                // 拷贝暂存的订单数据，以保留售中、售后、程序员等信息
                const payload = { ...this.currentOrderForReceipt };
                // 更新收款图片
                payload.receiptImages = newReceiptImagesString;

                updateOrders(payload).then(response => {
                    this.$modal.msgSuccess("删除成功");
                    this.currentReceiptImages = newReceiptImagesString;
                    this.currentReceiptImageList = images;
                    this.getList();
                }).catch(() => {
                    this.$modal.msgError("删除失败");
                });
            }).catch(() => { });
        },

        /** 格式化程序员信息显示 */
        formatProgrammerInfo(row) {
            if (!row.acceptedProgrammerId && !row.acceptedProgrammerName) {
                return '';
            }

            // 如果有 acceptedProgrammerId，解析任务类型和用户信息
            if (row.acceptedProgrammerId && typeof row.acceptedProgrammerId === 'string') {
                const assignments = row.acceptedProgrammerId.split(',');
                const formattedAssignments = assignments.map(assignment => {
                    const parts = assignment.trim().split('-');
                    if (parts.length === 2) {
                        const taskName = parts[0].trim();
                        const userId = parseInt(parts[1], 10);

                        // 查找对应的用户信息
                        const user = this.programmerUserOptions.find(u => u.value === userId);
                        if (user) {
                            return `${taskName}-${user.label}`;
                        } else {
                            return `${taskName}-用户${userId}`;
                        }
                    }
                    return assignment.trim();
                });

                return formattedAssignments.join(', ');
            }

            // 如果只有 acceptedProgrammerName，直接返回
            return row.acceptedProgrammerName || '';
        },

        /** 检查是否有售后权限 */
        checkAfterSalePermission() {
            // 通过API获取用户角色信息
            const userid = this.$store.state.user.id;
            if (userid) {
                // 这里需要根据实际的API来获取用户角色
                // 假设有一个获取用户角色的API
                this.$store.dispatch('GetInfo').then(() => {
                    const roles = this.$store.getters.roles || [];
                    this.hasAfterSalePermission = roles.some(role => role.includes('售后'));
                }).catch(() => {
                    this.hasAfterSalePermission = false;
                });
            } else {
                this.hasAfterSalePermission = false;
            }
        },

        /** 技术交付按钮操作 */
        handleTechnicalDelivery(row) {
            this.$modal.confirm(`确认将订单"${row.orderNo}"状态修改为技术交付（未过售后期）吗？`).then(() => {
                updateOrderStatusCloseSucceed(row.id).then(response => {
                    this.$modal.msgSuccess("技术交付操作成功")
                    this.getList() // 刷新列表
                }).catch(error => {
                    this.$modal.msgError("技术交付操作失败：" + (error.message || "未知错误"))
                })
            }).catch(() => {
                this.$modal.msgInfo("已取消技术交付操作")
            })
        },

        /** 客户确认按钮操作 */
        handleCustomerConfirm(row) {
            this.$modal.confirm(`确认将订单"${row.orderNo}"状态修改为客户确认（已完成）吗？`).then(() => {
                updateOrderStatusSucceed(row.id).then(response => {
                    this.$modal.msgSuccess("客户确认操作成功")
                    this.getList() // 刷新列表
                }).catch(error => {
                    this.$modal.msgError("客户确认操作失败：" + (error.message || "未知错误"))
                })
            }).catch(() => {
                this.$modal.msgInfo("已取消客户确认操作")
            })
        },

        /** 处理订单完成状态切换 */
        handleCompletionStatusSwitch(row, newStatus) {
            const statusNames = {
                1: '初稿已完成',
                2: '修改中',
                3: '终稿已确认'
            };
            
            const currentStatus = row.completionStatus;
            const newStatusInt = parseInt(newStatus);
            
            // 验证状态切换规则
            if (currentStatus === 1 && newStatusInt === 1) {
                this.$modal.msgWarning("状态1（初稿已完成）点击后不可再切换回状态1");
                return;
            }
            
            // 如果状态为2或3，必须已经达到状态1
            if ((newStatusInt === 2 || newStatusInt === 3) && (!currentStatus || currentStatus < 1)) {
                this.$modal.msgWarning("请先切换到【初稿已完成】状态");
                return;
            }
            
            const confirmMsg = currentStatus 
                ? `确认将订单"${row.orderNo}"的完成状态从"${statusNames[currentStatus]}"切换为"${statusNames[newStatusInt]}"吗？`
                : `确认将订单"${row.orderNo}"的完成状态设置为"${statusNames[newStatusInt]}"吗？`;
            
            this.$modal.confirm(confirmMsg).then(() => {
                switchCompletionStatus(row.id, newStatusInt).then(response => {
                    this.$modal.msgSuccess(`状态已切换为：${statusNames[newStatusInt]}`);
                    this.getList(); // 刷新列表
                }).catch(error => {
                    this.$modal.msgError("状态切换失败：" + (error.message || "未知错误"));
                });
            }).catch(() => {
                this.$modal.msgInfo("已取消状态切换");
            });
        },

        /** 生成需求图片 - 支持长文本完整显示 */
        async generateRequirementImage(orderData) {
            return new Promise((resolve, reject) => {
                const canvas = document.createElement('canvas');
                const ctx = canvas.getContext('2d');

                // 基础设置
                const baseWidth = 800;
                const leftMargin = 50;
                const rightMargin = 50;
                const topMargin = 80;
                const lineHeight = 30;
                const sectionSpacing = 20;
                const maxContentWidth = baseWidth - leftMargin - rightMargin;

                // 准备数据
                const fields = [
                    { label: '项目编号：', value: orderData.orderNo || '', isSingleLine: true },
                    { label: '项目名称：', value: orderData.orderTitle || '', isSingleLine: true },
                    { label: '开发语言：', value: orderData.techType || '', isSingleLine: true },
                    { label: '需求简介：', value: this.tempRequirementIntroduce || orderData.introduce || '', isSingleLine: false }
                ];

                // 计算所需高度
                let totalHeight = topMargin + 60; // 标题区域

                fields.forEach(field => {
                    // 设置字体来测量文本
                    ctx.font = 'bold 20px "Microsoft YaHei", Arial, sans-serif';
                    const labelWidth = ctx.measureText(field.label).width;

                    ctx.font = '18px "Microsoft YaHei", Arial, sans-serif';
                    const valueMaxWidth = maxContentWidth - labelWidth - 20;

                    if (field.isSingleLine) {
                        totalHeight += lineHeight + sectionSpacing;
                    } else {
                        // 计算多行文本所需高度
                        const lines = this.wrapTextForCanvas(ctx, field.value, valueMaxWidth);
                        totalHeight += Math.max(lineHeight, lines.length * lineHeight) + sectionSpacing;
                    }
                });

                totalHeight += 50; // 底部边距

                // 设置画布尺寸
                canvas.width = baseWidth;
                canvas.height = Math.max(600, totalHeight); // 最小高度600，根据内容自动增高

                // 绘制背景
                ctx.fillStyle = '#ffffff';
                ctx.fillRect(0, 0, canvas.width, canvas.height);

                // 绘制边框
                ctx.strokeStyle = '#e1e8ed';
                ctx.lineWidth = 2;
                ctx.strokeRect(5, 5, canvas.width - 10, canvas.height - 10);

                // 绘制内边框
                ctx.strokeStyle = '#f8f9fa';
                ctx.lineWidth = 1;
                ctx.strokeRect(20, 20, canvas.width - 40, canvas.height - 40);

                // 绘制标题
                ctx.fillStyle = '#1a1a1a';
                ctx.font = 'bold 32px "Microsoft YaHei", Arial, sans-serif';
                ctx.textAlign = 'center';
                ctx.fillText('项目需求单', canvas.width / 2, 60);

                // 绘制分割线
                ctx.strokeStyle = '#dee2e6';
                ctx.lineWidth = 1;
                ctx.beginPath();
                ctx.moveTo(leftMargin, 80);
                ctx.lineTo(canvas.width - rightMargin, 80);
                ctx.stroke();

                // 绘制内容
                let currentY = topMargin + 40;
                ctx.textAlign = 'left';

                fields.forEach(field => {
                    // 绘制标签
                    ctx.fillStyle = '#2c3e50';
                    ctx.font = 'bold 20px "Microsoft YaHei", Arial, sans-serif';
                    ctx.fillText(field.label, leftMargin, currentY);

                    const labelWidth = ctx.measureText(field.label).width;
                    const valueStartX = leftMargin + labelWidth + 10;
                    const valueMaxWidth = maxContentWidth - labelWidth - 10;

                    // 绘制值
                    ctx.fillStyle = '#34495e';
                    ctx.font = '18px "Microsoft YaHei", Arial, sans-serif';

                    if (field.isSingleLine) {
                        // 单行显示，如果超长则截断
                        const truncatedText = this.truncateTextForCanvas(ctx, field.value, valueMaxWidth);
                        ctx.fillText(truncatedText, valueStartX, currentY);
                        currentY += lineHeight + sectionSpacing;
                    } else {
                        // 多行显示，完整显示所有内容
                        const lines = this.wrapTextForCanvas(ctx, field.value, valueMaxWidth);
                        lines.forEach((line, index) => {
                            ctx.fillText(line, valueStartX, currentY + (index * lineHeight));
                        });
                        currentY += Math.max(lineHeight, lines.length * lineHeight) + sectionSpacing;
                    }
                });

                // 绘制底部信息
                ctx.fillStyle = '#7f8c8d';
                ctx.font = '14px "Microsoft YaHei", Arial, sans-serif';
                ctx.textAlign = 'center';
                ctx.fillText(`生成时间: ${new Date().toLocaleString('zh-CN')}`, canvas.width / 2, canvas.height - 20);

                // 转换为 Blob
                canvas.toBlob((blob) => {
                    if (blob) {
                        resolve(blob);
                    } else {
                        reject(new Error('生成图片失败'));
                    }
                }, 'image/png', 0.95);
            });
        },

        /** 改进的文本换行处理 - 确保完整显示所有内容 */
        wrapTextForCanvas(ctx, text, maxWidth) {
            if (!text) return [''];

            const lines = [];
            const paragraphs = text.split('\n'); // 处理换行符

            paragraphs.forEach(paragraph => {
                if (!paragraph.trim()) {
                    lines.push(''); // 保留空行
                    return;
                }

                let currentLine = '';
                const characters = paragraph.split('');

                for (let i = 0; i < characters.length; i++) {
                    const testLine = currentLine + characters[i];
                    const metrics = ctx.measureText(testLine);

                    if (metrics.width > maxWidth && currentLine !== '') {
                        lines.push(currentLine);
                        currentLine = characters[i];
                    } else {
                        currentLine = testLine;
                    }
                }

                if (currentLine) {
                    lines.push(currentLine);
                }
            });

            return lines.length > 0 ? lines : [''];
        },

        /** 文本截断处理（仅用于单行字段） */
        truncateTextForCanvas(ctx, text, maxWidth) {
            if (!text) return '';

            if (ctx.measureText(text).width <= maxWidth) {
                return text;
            }

            let truncated = text;
            const ellipsis = '...';

            while (truncated.length > 0) {
                const testText = truncated + ellipsis;
                if (ctx.measureText(testText).width <= maxWidth) {
                    return testText;
                }
                truncated = truncated.slice(0, -1);
            }

            return ellipsis;
        },

        /** 上传生成的图片 - 使用通用文件上传接口 */
        async uploadGeneratedImage(imageBlob) {
            console.log('=== 开始上传图片到通用文件接口 ===');
            console.log('参数信息:');
            console.log('- imageBlob大小:', imageBlob.size, 'bytes');
            console.log('- imageBlob类型:', imageBlob.type);

            const formData = new FormData();
            const fileName = `requirement_${Date.now()}.png`;
            formData.append('file', imageBlob, fileName);

            console.log('FormData信息:');
            console.log('- 文件名:', fileName);
            console.log('- FormData内容:');
            for (let pair of formData.entries()) {
                if (pair[1] instanceof File || pair[1] instanceof Blob) {
                    console.log(`  ${pair[0]}: [${pair[1].constructor.name}] 大小=${pair[1].size} 类型=${pair[1].type}`);
                } else {
                    console.log(`  ${pair[0]}: ${pair[1]}`);
                }
            }

            try {
                console.log('=== 调用通用文件上传接口 ===');
                console.log('使用API: uploadFile from @/api/system/file');

                const response = await uploadFile(formData);

                console.log('=== 上传响应 ===');
                console.log('响应数据:', response);
                console.log('响应类型:', typeof response);
                console.log('响应键:', Object.keys(response || {}));

                if (response && response.code === 200) {
                    console.log('上传成功，提取URL...');
                    const imageUrl = response.data?.url || response.data?.fileName || response.data;
                    console.log('提取到的图片URL:', imageUrl);
                    return imageUrl;
                } else {
                    console.error('上传失败，响应错误:', response?.msg || '未知错误');
                    throw new Error(response?.msg || '上传失败');
                }

            } catch (error) {
                console.log('=== 上传异常 ===');
                console.error('异常类型:', error.constructor.name);
                console.error('异常信息:', error.message);
                console.error('异常对象:', error);

                if (error.response) {
                    console.error('HTTP响应错误:');
                    console.error('- 状态码:', error.response.status);
                    console.error('- 状态文本:', error.response.statusText);
                    console.error('- 响应数据:', error.response.data);
                    console.error('- 响应头:', error.response.headers);
                }

                if (error.request) {
                    console.error('HTTP请求错误:');
                    console.error('- 请求对象:', error.request);
                }

                console.error('完整错误堆栈:', error.stack);

                // 抛出详细错误信息
                if (error.code === 'ECONNABORTED') {
                    throw new Error('图片上传超时，请重试');
                }

                const errorMsg = error.response?.data?.msg || error.message || '未知错误';
                throw new Error(`图片上传失败: ${errorMsg}`);
            }
        }

    }
}
</script>

<style scoped>
.ios-style-container {
    background-color: #f0f2f5;
    padding: 20px;
    height: calc(100vh - 84px);
    display: flex;
    flex-direction: column;
}

.table-wrapper {
    flex: 1;
    overflow: hidden;
}

/* .table-wrapper::v-deep .status-cell-blue {
  background-color: #409eff !important;
  color: white;
}
.table-wrapper::v-deep .status-cell-yellow {
  background-color: #E6A23C !important;
  color: white;
}
.table-wrapper::v-deep .status-cell-red {
  background-color: #F56C6C !important;
  color: white;
}
.table-wrapper::v-deep .status-cell-purple {
  background-color: #673ab7 !important;
  color: white;
}
.table-wrapper::v-deep .status-cell-green {
  background-color: #67C23A !important;
  color: white;
} */


.table-wrapper ::-webkit-scrollbar {
    width: 12px;
    /* 垂直滚动条宽度 */
    height: 12px;
    /* 水平滚动条高度 */
}

/* 设置整个页面容器的滚动条宽度 */
.ios-style-container ::-webkit-scrollbar {
    width: 12px;
    height: 12px;
}

.status-counts-wrapper {
    margin-bottom: 10px;
}

.status-counts-container {
    display: flex;
    flex-wrap: nowrap;
    gap: 15px;
    overflow-x: auto;
    white-space: nowrap;
    padding-bottom: 5px;
}

.status-counts-container::-webkit-scrollbar {
    height: 6px;
}

.status-counts-container::-webkit-scrollbar-track {
    background: #f1f1f1;
    border-radius: 3px;
}

.status-counts-container::-webkit-scrollbar-thumb {
    background: #c1c1c1;
    border-radius: 3px;
}

.status-counts-container::-webkit-scrollbar-thumb:hover {
    background: #a8a8a8;
}

.status-count-item {
    display: flex;
    align-items: center;
    gap: 8px;
    flex-shrink: 0;
    white-space: nowrap;
}

.status-label {
    font-size: 14px;
    color: #606266;
}

.status-count-tag {
    color: white;
}

.tag-white-black {
    background-color: white !important;
    color: black !important;
    border: 1px solid #DCDFE6 !important;
    /* Adding a light grey border for the box effect */
}

.tag-blue-black {
    background-color: #409EFF !important;
    /* Element UI Primary Blue */
    color: black !important;
    border: 1px solid #409EFF !important;
}

.tag-red-black {
    background-color: #F56C6C !important;
    /* Element UI Danger Red */
    color: black !important;
    border: 1px solid #F56C6C !important;
}

.introduce-text {
    display: inline-block;
    max-width: 100%;
    overflow: hidden;
    text-overflow: ellipsis;
    white-space: nowrap;
    vertical-align: middle;
}

.tag-yellow-black {
    background-color: #E6A23C !important;
    /* Element UI Warning Yellow */
    color: black !important;
    border: 1px solid #E6A23C !important;
}

.tag-green-black {
    background-color: #67C23A !important;
    /* Element UI Success Green */
    color: black !important;
    border: 1px solid #67C23A !important;
}

/* 快速筛选区域样式 */
.quick-filter-container {
    background: white;
    padding: 15px;
    margin-bottom: 10px;
    border-radius: 4px;
    box-shadow: 0 1px 4px rgba(0, 0, 0, 0.08);
    border-left: 4px solid #409EFF;
}

.quick-filter-title {
    display: flex;
    align-items: center;
    margin-bottom: 15px;
    font-size: 14px;
    font-weight: 600;
    color: #409EFF;
}

.quick-filter-title i {
    margin-right: 8px;
    font-size: 16px;
}


.ios-style-container {
    background-color: #f5f7fa;
    padding: 16px;
    height: calc(100vh - 84px);
    display: flex;
    flex-direction: column;
}

.table-wrapper {
    flex: 1;
    overflow: hidden;
    background: #fff;
    border-radius: 4px;
    box-shadow: 0 1px 4px rgba(0, 0, 0, 0.08);
}

/* 状态行样式 - 使用CSS变量 */
.table-wrapper ::v-deep .el-table {
    /* 待抢单 - 灰色 */
    --pending-bg: #F5F5F5;
    --pending-text: #565656;
    --pending-border: #9E9E9E;

    /* 重包单 - 浅绿色 */
    --accepted-bg: #82E0AA;
    --accepted-text: #000000;
    --accepted-border: #2E7D32;

    /* 进行中 - 蓝色 */
    --processing-bg: #E3F2FD;
    --processing-text: #1976D2;
    --processing-border: #1976D2;

    /* 已完成 - 红色 */
    --completed-bg: #E74C3C;
    --completed-text: #000000;
    --completed-border: #D32F2F;

    /* 半成品 - 紫色 */
    --half-bg: #df00ff;
    --half-text: #000000;
    --half-border: #7409a2;

    /* 服务费 - 橘色 */
    --service-fee-bg: #ff9600;
    --service-fee-text: #000000;
    --service-fee-border: #ff8000;

    /* 已退单 - 黄色 */
    --refunded-bg: #ffe600;
    --refunded-text: rgba(0, 0, 0, 0.93);
    --refunded-border: #fbea04;
}

/* 各状态行样式 */
.table-wrapper ::v-deep .el-table .row-pending td {
    background-color: var(--pending-bg) !important;
    border-bottom: 1px solid var(--pending-border) !important;
}

.table-wrapper ::v-deep .el-table .row-pending .cell {
    color: var(--pending-text) !important;
}

.table-wrapper ::v-deep .el-table .row-accepted td {
    background-color: var(--accepted-bg) !important;
    border-bottom: 1px solid var(--accepted-border) !important;
}

.table-wrapper ::v-deep .el-table .row-accepted .cell {
    color: var(--accepted-text) !important;
}

.table-wrapper ::v-deep .el-table .row-processing td {
    background-color: var(--processing-bg) !important;
    border-bottom: 1px solid var(--processing-border) !important;
}

.table-wrapper ::v-deep .el-table .row-processing .cell {
    color: var(--processing-text) !important;
}

.table-wrapper ::v-deep .el-table .row-completed td {
    background-color: var(--completed-bg) !important;
    border-bottom: 1px solid var(--completed-border) !important;
}

.table-wrapper ::v-deep .el-table .row-completed .cell {
    color: var(--completed-text) !important;
}

.table-wrapper ::v-deep .el-table .row-half td {
    background-color: var(--half-bg) !important;
    border-bottom: 1px solid var(--half-border) !important;
}

.table-wrapper ::v-deep .el-table .row-half .cell {
    color: var(--half-text) !important;
}

.table-wrapper ::v-deep .el-table .row-service-fee td {
    background-color: var(--service-fee-bg) !important;
    border-bottom: 1px solid var(--service-fee-border) !important;
}

.table-wrapper ::v-deep .el-table .row-service-fee .cell {
    color: var(--service-fee-text) !important;
}

.table-wrapper ::v-deep .el-table .row-refunded td {
    background-color: var(--refunded-bg) !important;
    border-bottom: 1px solid var(--refunded-border) !important;
}

.table-wrapper ::v-deep .el-table .row-refunded .cell {
    color: var(--refunded-text) !important;
}

/* 状态标签样式 - 保持与行颜色一致 */
.status-tag {
    padding: 0 8px;
    height: 24px;
    line-height: 22px;
    font-size: 12px;
    border-radius: 4px;
    display: inline-flex;
    align-items: center;
    justify-content: center;
}

.status-tag-pending {
    background-color: var(--pending-bg) !important;
    color: var(--pending-text) !important;
    border: 1px solid var(--pending-border) !important;
}

.status-tag-accepted {
    background-color: var(--accepted-bg) !important;
    color: var(--accepted-text) !important;
    border: 1px solid var(--accepted-border) !important;
}

.status-tag-processing {
    background-color: var(--processing-bg) !important;
    color: var(--processing-text) !important;
    border: 1px solid var(--processing-border) !important;
}

.status-tag-completed {
    background-color: var(--completed-bg) !important;
    color: var(--completed-text) !important;
    border: 1px solid var(--completed-border) !important;
}

.status-tag-half {
    background-color: var(--half-bg) !important;
    color: var(--half-text) !important;
    border: 1px solid var(--half-border) !important;
}

.status-tag-service-fee {
    background-color: var(--service-fee-bg) !important;
    color: var(--service-fee-text) !important;
    border: 1px solid var(--service-fee-border) !important;
}

.status-tag-refunded {
    background-color: var(--refunded-bg) !important;
    color: var(--refunded-text) !important;
    border: 1px solid var(--refunded-border) !important;
}

/* 表格悬停效果 */
.table-wrapper ::v-deep .el-table--enable-row-hover .el-table__body tr:hover>td {
    opacity: 0.7;
    transition: opacity 0.2s;
}

/* 收款状态约束提示样式 */
.status-constraint-tip {
    margin-top: 5px;
    padding: 8px 12px;
    background-color: #f0f9ff;
    border: 1px solid #bae6fd;
    border-radius: 6px;
    font-size: 12px;
    color: #0369a1;
}

.status-constraint-tip>div:first-child {
    display: flex;
    align-items: center;
    gap: 6px;
    margin-bottom: 8px;
}

.status-constraint-tip i {
    color: #0ea5e9;
    font-size: 14px;
}

.next-available-options {
    display: flex;
    align-items: center;
    flex-wrap: wrap;
    gap: 5px;
    font-size: 11px;
    color: #0369a1;
}

/* 收款图片预览样式 */
.receipt-images-preview {
    display: flex;
    flex-wrap: wrap;
    gap: 10px;
}

.receipt-images-preview .image-item {
    position: relative;
    display: inline-block;
}

.image-item .delete-icon {
    position: absolute;
    top: 5px;
    right: 5px;
    background-color: rgba(0, 0, 0, 0.5);
    color: white;
    border-radius: 50%;
    width: 20px;
    height: 20px;
    display: flex;
    justify-content: center;
    align-items: center;
    cursor: pointer;
    opacity: 0;
    transition: opacity 0.3s;
}

.image-item:hover .delete-icon {
    opacity: 1;
}

/* 需求图片预览样式 */
.demand-images-preview {
    display: flex;
    flex-wrap: wrap;
    gap: 10px;
}

.demand-images-preview .image-item {
    position: relative;
    display: inline-block;
}

/* 文件列表样式 */
.file-list {
    margin-top: 15px;
}

.file-list h4 {
    margin: 10px 0;
    color: #303133;
    font-size: 14px;
    font-weight: 600;
}

.file-list ul {
    list-style: none;
    padding: 0;
    margin: 0;
}

.file-item {
    display: flex;
    justify-content: space-between;
    align-items: center;
    padding: 8px 12px;
    margin-bottom: 5px;
    background-color: #f8f9fa;
    border: 1px solid #e9ecef;
    border-radius: 4px;
    transition: background-color 0.2s;
}

.file-item:hover {
    background-color: #e9ecef;
}

.file-link {
    flex: 1;
    color: #409eff;
    text-decoration: none;
    overflow: hidden;
    text-overflow: ellipsis;
    white-space: nowrap;
    margin-right: 10px;
}

.file-link:hover {
    color: #66b1ff;
    text-decoration: underline;
}

.delete-btn {
    flex-shrink: 0;
    margin-left: 10px;
}
</style>
